71

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!

0

2 Answers 2

142

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***********'
Sign up to request clarification or add additional context in comments.

4 Comments

@Brett -- It looks like those are deprecated. I've updated with another alternative which isn't ;-)
The 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.
how do you make 30 a variable?
@Raksha -- something like '{:>{width}}'.format('right aligned', width=30) works.
17

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        

2 Comments

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}}'.
If the string has embedded escape characters (e.g. for coloring), this does not work. Somehow the number of displayed characters is not calculated correctly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.