Display number with leading zeros

后端 未结 16 2322
我在风中等你
我在风中等你 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:05
    width = 5
    num = 3
    formatted = (width - len(str(num))) * "0" + str(num)
    print formatted
    
    0 讨论(0)
  • 2020-11-22 03:06

    Use:

    '00'[len(str(i)):] + str(i)
    

    Or with the math module:

    import math
    '00'[math.ceil(math.log(i, 10)):] + str(i)
    
    0 讨论(0)
  • 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
    >>> 
    
    0 讨论(0)
  • 2020-11-22 03:08

    You can use str.zfill:

    print(str(1).zfill(2))
    print(str(10).zfill(2))
    print(str(100).zfill(2))
    

    prints:

    01
    10
    100
    
    0 讨论(0)
  • 2020-11-22 03:09

    Or this:

    print '{0:02d}'.format(1)

    0 讨论(0)
  • 2020-11-22 03:10

    Or another solution.

    "{:0>2}".format(number)
    
    0 讨论(0)
提交回复
热议问题