Display number with leading zeros

后端 未结 16 2324
我在风中等你
我在风中等你 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:21

    You can do this with f strings.

    import numpy as np
    
    print(f'{np.random.choice([1, 124, 13566]):0>8}')
    

    This will print constant length of 8, and pad the rest with leading 0.

    00000001
    00000124
    00013566
    
    0 讨论(0)
  • 2020-11-22 03:23

    In Python 2.6+ and 3.0+, you would use the format() string method:

    for i in (1, 10, 100):
        print('{num:02d}'.format(num=i))
    

    or using the built-in (for a single number):

    print(format(i, '02d'))
    

    See the PEP-3101 documentation for the new formatting functions.

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

    In Python >= 3.6, you can do this succinctly with the new f-strings that were introduced by using:

    f'{val:02}'
    

    which prints the variable with name val with a fill value of 0 and a width of 2.

    For your specific example you can do this nicely in a loop:

    a, b, c = 1, 10, 100
    for val in [a, b, c]:
        print(f'{val:02}')
    

    which prints:

    01 
    10
    100
    

    For more information on f-strings, take a look at PEP 498 where they were introduced.

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

    If dealing with numbers that are either one or two digits:

    '0'+str(number)[-2:] or '0{0}'.format(number)[-2:]

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