How to pad zeroes to a string?

前端 未结 17 1980
醉酒成梦
醉酒成梦 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:40

    Besides zfill, you can use general string formatting:

    print(f'{number:05d}') # (since Python 3.6), or
    print('{:05d}'.format(number)) # or
    print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
    print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
    print(format(number, '05d'))
    

    Documentation for string formatting and f-strings.

提交回复
热议问题