python - How to zero pad an f-string? - Stack Overflow
f-string and string right padding is driving me crazy
How to pad a string with leading zeros in Python 3 - Stack Overflow
Strange behavior: leading zeros in formatted print function are reversed
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.
Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
It important to note that Python 2 is no longer supported.
Sample usage:
print(str(1).zfill(3))
# Expected output: 001
Description:
When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
Since python 3.6 you can use f-string :
>>> length = "1"
>>> print(f'length = {length:03}')
length = 100
>>> print(f'length = {length:>03}')
length = 001