How to pad zeroes to a string?

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

    width = 10
    x = 5
    print "%0*d" % (width, x)
    > 0000000005
    

    See the print documentation for all the exciting details!

    Update for Python 3.x (7.5 years later)

    That last line should now be:

    print("%0*d" % (width, x))
    

    I.e. print() is now a function, not a statement. Note that I still prefer the Old School printf() style because, IMNSHO, it reads better, and because, um, I've been using that notation since January, 1980. Something ... old dogs .. something something ... new tricks.

提交回复
热议问题