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 OverflowYou 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
python - Display number with leading zeros - Stack Overflow
How would you add zeros to the beginning of an Integer, such that there are 4 total digits in the number?
How to convert int with more zero digits to string in python? - Stack Overflow
Strange behavior: leading zeros in formatted print function are reversed
In Python 2 (and Python 3) you can do:
number = 1
print("%02d" % (number,))
Basically % is like printf or sprintf (see docs).
For Python 3.+, the same behavior can also be achieved with format:
number = 1
print("{:02d}".format(number))
For Python 3.6+ the same behavior can be achieved with f-strings:
number = 1
print(f"{number:02d}")
You can use str.zfill:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
prints:
01
10
100
Without using zfill or format or any other obscure functions.
example:
turn 15 into 0015
or 234 into 0234
Pad your string.
print('{:0>4}'.format(str(1)))
prints 0001 while
print('{:0>4}'.format(str(123456)))
prints 123456.
You can check https://pyformat.info for more info on .format().
In the example by Jonathan, 0045 becomes 37 because 0045 is considered as octal by the interpreter. 4*8+5=37. Usually in cases like this, we will not start with leading zeroes. we will start with 45. Hence the answer will be consistent. leading zeroes in string form provide a way for the interpreter to understand octal representation. Hope this helps.