How to pad zeroes to a string?

前端 未结 17 1963
醉酒成梦
醉酒成梦 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条回答
  •  -上瘾入骨i
    2020-11-21 23:31

    Another approach would be to use a list comprehension with a condition checking for lengths. Below is a demonstration:

    # input list of strings that we want to prepend zeros
    In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]
    
    # prepend zeros to make each string to length 8, if length of string is less than 8
    In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
    Out[83]: ['00101010', '10101010', '00011110', '00000000']
    

提交回复
热议问题