67

I have two scenarios where I need to pad a string with whitespaces up to a certain length, in both the left and right directions (in separate cases). For instance, I have the string:

TEST

but I need to make the string variable

_____TEST1

so that the actual string variable is 10 characters in length (led by 5 spaces in this case). NOTE: I am showing underscores to represent whitespace (the markdown doesn't look right on SO otherwise).

I also need to figure out how to reverse it and pad whitespace from the other direction:

TEST2_____

Are there any string helper functions to do this? Or would I need to create a character array to manage it?

Also note, that I am trying to keep the string length a variable (I used a length of 10 in the examples above, but I'll need to be able to change this).

Any help would be awesome. If there are any python functions to manage this, I'd rather avoid having to write something from the ground up.

Thanks!

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Brett
  • 11,637
  • 34
  • 127
  • 213

2 Answers2

139

You can look into str.ljust and str.rjust I believe.

The alternative is probably to use the format method:

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'
Nikolay Vasiliev
  • 5,656
  • 22
  • 31
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 2
    @Brett -- It looks like those are deprecated. I've updated with another alternative which isn't ;-) – mgilson Feb 08 '13 at 16:18
  • 16
    The [`str.ljust`](https://docs.python.org/2/library/stdtypes.html#str.ljust) and `rjust` methods are _not_ deprecated; you just linked to the ancient functions from the `string` module, which were only needed in the pre-2.3 days when builtin types weren't like classes and only had methods as a special case. – abarnert May 02 '15 at 10:35
  • how do you make 30 a variable? – Raksha Dec 29 '18 at 23:30
  • 4
    @Raksha -- something like `'{:>{width}}'.format('right aligned', width=30)` works. – mgilson Dec 30 '18 at 01:38
15

Via f-strings (Python 3.6+) :

>>> l = "left aligned"
>>> print(f"{l:<30}")
left aligned                  

>>> r = "right aligned"
>>> print(f"{r:>30}")
                 right aligned

>>> c = "center aligned"
>>> print(f"{c:^30}")
        center aligned        
Community
  • 1
  • 1
Ashton Honnecke
  • 688
  • 10
  • 16
  • 5
    However, these are not f-string-specific and only work when you want to align a string (not a number or, say, a tuple or list). You can use exactly the same syntax in f-strings as in format, as in the other answer. So, for example: `f'{right_stuff:>{width}}'` or `f'{left_stuff:<{width}}'`. – Fritz Feb 11 '20 at 19:39