You can use the zfill() method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
Answer from unbeknown on Stack OverflowShould I use zfill or an f-string?
Does zfill change the original string?
How do I add leading zeros in Python?
You can use the zfill() method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.
To output a string of length 5:
... in Python 3.5 and above: f-strings.
i = random.randint(0, 99999)
print(f'{i:05d}')
Search for f-strings here for more details.
... Python 2.6 and above:
print '{0:05d}'.format(i)
... before Python 2.6:
print "%05d" % i
See: https://docs.python.org/3/library/string.html
Without using zfill or format or any other obscure functions.
example:
turn 15 into 0015
or 234 into 0234
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'
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.