Display number with leading zeros

后端 未结 16 2323
我在风中等你
我在风中等你 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:12
    print('{:02}'.format(1))
    print('{:02}'.format(10))
    print('{:02}'.format(100))
    

    prints:

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

    The Pythonic way to do this:

    str(number).rjust(string_width, fill_char)
    

    This way, the original string is returned unchanged if its length is greater than string_width. Example:

    a = [1, 10, 100]
    for num in a:
        print str(num).rjust(2, '0')
    

    Results:

    01
    10
    100
    
    0 讨论(0)
  • 2020-11-22 03:14
    x = [1, 10, 100]
    for i in x:
        print '%02d' % i
    

    results in:

    01
    10
    100
    

    Read more information about string formatting using % in the documentation.

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

    Use a format string - http://docs.python.org/lib/typesseq-strings.html

    For example:

    python -c 'print "%(num)02d" % {"num":5}'
    
    0 讨论(0)
  • 2020-11-22 03:18

    In Python 2 (and Python 3) you can do:

    print "%02d" % (1,)
    

    Basically % is like printf or sprintf (see docs).


    For Python 3.+, the same behavior can also be achieved with format:

    print("{:02d}".format(1))
    

    For Python 3.6+ the same behavior can be achieved with f-strings:

    print(f"{1:02d}")
    
    0 讨论(0)
  • 2020-11-22 03:20
    df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))
    

    The 5 is the number of total digits.

    I used this link: http://www.datasciencemadesimple.com/add-leading-preceding-zeros-python/

    0 讨论(0)
提交回复
热议问题