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!'
Videos
I know this is dumb, but something is strange. Everything works from the python3 interpreter but in my code it doesn't work. All I want is a string to be padded to the right.
This doesn't work
ename = f'"{endpoint}"'
print(f'{header} {ename:<30}!') I always get a single space before the ! I expect to get this (which I get in the interactive mode)
HEADER ENAME....................!
(note: I put dots there to make the spaces clear, they should be spaces!)
But I get
HEADER ENAME.!
If I change it to this, it works
ename = f'"{endpoint}"'
print(f'{header} {ename:!<30}!')But the padding is ! marks. (which was a test). If I change the ! to a space, that doesn't work.
Clearly I'm being dumb and missing something important. What an I missing? Thanks.
UPDATE: Appears to be caused by some post processing after python runs. Not sure what it is, but I don't believe it's python at the moment. Strange indeed!
UPDATE2: Well, I'm dumb. Problem was that this ultimately went through an HTML renderer and that would remove multiple spaces (exactly as it should). So 100% not a python issue. Thanks to all.