How to pad zeroes to a string?

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

    For the ones who came here to understand and not just a quick answer. I do these especially for time strings:

    hour = 4
    minute = 3
    "{:0>2}:{:0>2}".format(hour,minute)
    # prints 04:03
    
    "{:0>3}:{:0>5}".format(hour,minute)
    # prints '004:00003'
    
    "{:0<3}:{:0<5}".format(hour,minute)
    # prints '400:30000'
    
    "{:$<3}:{:#<5}".format(hour,minute)
    # prints '4$$:3####'
    

    "0" symbols what to replace with the "2" padding characters, the default is an empty space

    ">" symbols allign all the 2 "0" character to the left of the string

    ":" symbols the format_spec

提交回复
热议问题