Display number with leading zeros

后端 未结 16 2532
我在风中等你
我在风中等你 2020-11-22 03:00

Given:

a = 1
b = 10
c = 100

How do I display a leading zero for all numbers with less than two digits?

This is the output I\'m expe

16条回答
  •  滥情空心
    2020-11-22 03:07

    This is how I do it:

    str(1).zfill(len(str(total)))
    

    Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:

    Python 3.6.5 (default, May 11 2018, 04:00:52) 
    [GCC 8.1.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> total = 100
    >>> print(str(1).zfill(len(str(total))))
    001
    >>> total = 1000
    >>> print(str(1).zfill(len(str(total))))
    0001
    >>> total = 10000
    >>> print(str(1).zfill(len(str(total))))
    00001
    >>> 
    

提交回复
热议问题