Python – How can I pad a string with spaces from the right and left?

Question:

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!

Asked By: Brett

||

Answers:

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***********'
Answered By: mgilson

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        
Answered By: Ashton Honnecke
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.