How do I format a number with a variable number of digits in Python?

PythonStringString FormattingNumber Formatting

Python Problem Overview


Say I wanted to display the number 123 with a variable number of padded zeroes on the front.

For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:

00123

If I wanted to display it in 6 digits I would have digits = 6 giving:

000123

How would I do this in Python?

Python Solutions


Solution 1 - Python

If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting

>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'

See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings

Here is an example with variable width

>>> '{num:0{width}}'.format(num=123, width=6)
'000123'

You can even specify the fill char as a variable

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'

Solution 2 - Python

There is a string method called zfill:

>>> '12344'.zfill(10)
0000012344

It will pad the left side of the string with zeros to make the string length N (10 in this case).

Solution 3 - Python

'%0*d' % (5, 123)

Solution 4 - Python

With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to access previously defined variables with a briefer syntax:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

The examples given by John La Rooy can be written as

In [1]: num=123
   ...: fill='0'
   ...: width=6
   ...: f'{num:{fill}{width}}'

Out[1]: '000123'

Solution 5 - Python

For those who want to do the same thing with python 3.6+ and f-Strings this is the solution.

width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")

Solution 6 - Python

print "%03d" % (43)

Prints

> 043

Solution 7 - Python

Use string formatting

print '%(#)03d' % {'#': 2}
002
print '%(#)06d' % {'#': 123}
000123

More info here: link text

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEddyView Question on Stackoverflow
Solution 1 - PythonJohn La RooyView Answer on Stackoverflow
Solution 2 - PythonDonald MinerView Answer on Stackoverflow
Solution 3 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 4 - PythonjoelostblomView Answer on Stackoverflow
Solution 5 - PythonPraveen KulkarniView Answer on Stackoverflow
Solution 6 - Pythonst0leView Answer on Stackoverflow
Solution 7 - PythonBlue PeppersView Answer on Stackoverflow