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!'
String Format Padding
Allow f-string to dynamically pad spaces
f-string and string right padding is driving me crazy
How can I easily pad a float with x zeros on the left and round/pad to y decimal places on the right?
Hi there. I'd like some help on the following.
What I'm trying to output
_8:30_PM
note the underscore is a space because of reddit's markdown. It's representing a space
What I know
return '%2d:%2d PM' %(hour,minute)
If the minute is 2 i have to pad it with 02. If the hour is 3 I have to pad it to _3.
I don't know how to do the latter (pad the minute)