How to pad zeroes to a string?

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

    You could also repeat "0", prepend it to str(n) and get the rightmost width slice. Quick and dirty little expression.

    def pad_left(n, width, pad="0"):
        return ((pad * width) + str(n))[-width:]
    

提交回复
热议问题