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
How would you add zeros to the beginning of an Integer, such that there are 4 total digits in the number?
Need zeros before the number in int
python - Display number with leading zeros - Stack Overflow
In Python, how to specify a format when converting int to string? - Stack Overflow
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.
Without using zfill or format or any other obscure functions.
example:
turn 15 into 0015
or 234 into 0234
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
"%04d" where the 4 is the constant length will do what you described.
You can read about string formatting here.
Update for Python 3:
{:04d} is the equivalent for strings using the str.format method or format builtin function. See the format specification mini-language documentation.
You could use the zfill function of str class. Like so -
>>> str(165).zfill(4)
'0165'
One could also do %04d etc. like the others have suggested. But I thought this is more pythonic way of doing this...