How to pad zeroes to a string?

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

    When using Python >= 3.6, the cleanest way is to use f-strings with string formatting:

    >>> s = f"{1:08}"  # inline with int
    >>> s
    '00000001'
    
    >>> s = f"{'1':0>8}"  # inline with str
    >>> s
    '00000001'
    
    >>> n = 1
    >>> s = f"{n:08}"  # int variable
    >>> s
    '00000001'
    
    >>> c = "1"
    >>> s = f"{c:0>8}"  # str variable
    >>> s
    '00000001'
    

    I would prefer formatting with an int, since only then the sign is handled correctly:

    >>> f"{-1:08}"
    '-0000001'
    
    >>> f"{1:+08}"
    '+0000001'
    
    >>> f"{'-1':0>8}"
    '000000-1'
    

提交回复
热议问题