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 '
Answer from Felix Kling on Stack OverflowYou 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 f-strings
>>> f'{"Hi": <16} StackOverflow!' # Python >= 3.6
'Hi StackOverflow!'
or the str.format() method
>>> '{0: <16} StackOverflow!'.format('Hi') # Python >=2.6
'Hi StackOverflow!'
python - How can I pad a string with spaces from the right and left? - Stack Overflow
Allow f-string to dynamically pad spaces
Python 3, best way to pad/remove spaces in between strings?
String Format Padding
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***********'
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
Lets say I have several strings like:
name = "John" occupation = "Plumber"
I want it to print out in such a way that name starts at the very left and occupation starts 15 characters from the left. So if name was "Christian" then there would be less space in between Christian and Plumber than John and Plumber because Christian is longer.
Example output:
John Plumber Christian Plumber