How to pad zeroes to a string?

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

    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'
    

提交回复
热议问题