How can I fill out a Python string with spaces?
You can do this with str.ljust(width[, fillchar])
:
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than
len(s)
.
>>> 'hi'.ljust(10)
'hi '
For a flexible method that works even when formatting complicated string, you probably should use the string-formatting mini-language, using either the str.format()
method
>>> '{0: <16} StackOverflow!'.format('Hi') # Python >=2.6
'Hi StackOverflow!'
of f-strings
>>> f'{"Hi": <16} StackOverflow!' # Python >= 3.6
'Hi StackOverflow!'