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

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***********'

Python3 f string usage

l = "left aligned"
print(f"{l.ljust(30)}")

r = "right aligned"
print(f"{r.rjust(30)}")

c = "center aligned"
print(f"{c.center(30)}")

>>> l = "left aligned"
>>> print(f"{l.ljust(30)}")
left aligned                  

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

>>> print(f"{c.center(30)}")
        center aligned        

Tags:

Python

String