How to pad zeroes to a string?

前端 未结 17 1959
醉酒成梦
醉酒成梦 2020-11-21 22:59

What is a Pythonic way to pad a numeric string with zeroes to the left, i.e. so the numeric string has a specific length?

相关标签:
17条回答
  • 2020-11-21 23:18

    Strings:

    >>> n = '4'
    >>> print(n.zfill(3))
    004
    

    And for numbers:

    >>> n = 4
    >>> print(f'{n:03}') # Preferred method, python >= 3.6
    004
    >>> print('%03d' % n)
    004
    >>> print(format(n, '03')) # python >= 2.6
    004
    >>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
    004
    >>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
    004
    >>> print('{:03d}'.format(n))  # python >= 2.7 + python3
    004
    

    String formatting documentation.

    0 讨论(0)
  • 2020-11-21 23:21

    For zip codes saved as integers:

    >>> a = 6340
    >>> b = 90210
    >>> print '%05d' % a
    06340
    >>> print '%05d' % b
    90210
    
    0 讨论(0)
  • 2020-11-21 23:23

    Quick timing comparison:

    setup = '''
    from random import randint
    def test_1():
        num = randint(0,1000000)
        return str(num).zfill(7)
    def test_2():
        num = randint(0,1000000)
        return format(num, '07')
    def test_3():
        num = randint(0,1000000)
        return '{0:07d}'.format(num)
    def test_4():
        num = randint(0,1000000)
        return format(num, '07d')
    def test_5():
        num = randint(0,1000000)
        return '{:07d}'.format(num)
    def test_6():
        num = randint(0,1000000)
        return '{x:07d}'.format(x=num)
    def test_7():
        num = randint(0,1000000)
        return str(num).rjust(7, '0')
    '''
    import timeit
    print timeit.Timer("test_1()", setup=setup).repeat(3, 900000)
    print timeit.Timer("test_2()", setup=setup).repeat(3, 900000)
    print timeit.Timer("test_3()", setup=setup).repeat(3, 900000)
    print timeit.Timer("test_4()", setup=setup).repeat(3, 900000)
    print timeit.Timer("test_5()", setup=setup).repeat(3, 900000)
    print timeit.Timer("test_6()", setup=setup).repeat(3, 900000)
    print timeit.Timer("test_7()", setup=setup).repeat(3, 900000)
    
    
    > [2.281613943830961, 2.2719342631547077, 2.261691106209631]
    > [2.311480238815406, 2.318420542148333, 2.3552384305184493]
    > [2.3824197456864304, 2.3457239951596485, 2.3353268829498646]
    > [2.312442972404032, 2.318053102249902, 2.3054072168069872]
    > [2.3482314132374853, 2.3403386400002475, 2.330108825844775]
    > [2.424549090688892, 2.4346475296851438, 2.429691196530058]
    > [2.3259756401716487, 2.333549212826732, 2.32049893822186]
    

    I've made different tests of different repetitions. The differences are not huge, but in all tests, the zfill solution was fastest.

    0 讨论(0)
  • 2020-11-21 23:26

    For the ones who came here to understand and not just a quick answer. I do these especially for time strings:

    hour = 4
    minute = 3
    "{:0>2}:{:0>2}".format(hour,minute)
    # prints 04:03
    
    "{:0>3}:{:0>5}".format(hour,minute)
    # prints '004:00003'
    
    "{:0<3}:{:0<5}".format(hour,minute)
    # prints '400:30000'
    
    "{:$<3}:{:#<5}".format(hour,minute)
    # prints '4$$:3####'
    

    "0" symbols what to replace with the "2" padding characters, the default is an empty space

    ">" symbols allign all the 2 "0" character to the left of the string

    ":" symbols the format_spec

    0 讨论(0)
  • 2020-11-21 23:27

    For Python 3.6+ using f-strings:

    >>> i = 1
    >>> f"{i:0>2}"  # Works for both numbers and strings.
    '01'
    >>> f"{i:02}"  # Works only for numbers.
    '01'
    

    For Python 2 to Python 3.5:

    >>> "{:0>2}".format("1")  # Works for both numbers and strings.
    '01'
    >>> "{:02}".format(1)  # Works only for numbers.
    '01'
    
    0 讨论(0)
  • 2020-11-21 23:27

    str(n).zfill(width) will work with strings, ints, floats... and is Python 2.x and 3.x compatible:

    >>> n = 3
    >>> str(n).zfill(5)
    '00003'
    >>> n = '3'
    >>> str(n).zfill(5)
    '00003'
    >>> n = '3.0'
    >>> str(n).zfill(5)
    '003.0'
    
    0 讨论(0)
提交回复
热议问题