Search code examples
pythonstringstring-formattingnumber-formatting

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


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?


Solution

  • 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).