How to pad zeroes to a string?

前端 未结 17 1986
醉酒成梦
醉酒成梦 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题