How can I pad a string with spaces from the right and left? [duplicate]

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

Leave a Comment