How to pad zeroes to a string?

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

提交回复
热议问题