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.
Answer from nyedidikeke on Stack OverflowDoes zfill change the original string?
Should I use zfill or an f-string?
How do I add leading zeros in Python?
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
I’m trying to learn all of Python’s built-in functions before starting OOP, so I’m curious how this function could be used in real projects.
As maybe a alternative more portable [1] and efficient [2], actually you can just use str.ljust.
In [2]: '190'.ljust(8, '0')
Out[2]: '19000000'
In [3]: str.ljust?
Docstring:
S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
Type: method_descriptor
[1] format is not present on old python versions. format specifier was added since Python 3.0 (see PEP 3101) and Python 2.6.
[2] reverse twice is an expensive operation.
See Format Specification Mini-Language:
In [1]: '{:<08d}'.format(190)
Out[1]: '19000000'
In [2]: '{:>08d}'.format(190)
Out[2]: '00000190'
This also works with the Formatted String Literals, or f-strings for short (New in version 3.6):
In [1]: f'{190:<08d}'
Out[1]: '19000000'
In [2]: f'{190:>08d}'
Out[2]: '00000190'