开发者

Python: How do I convert an int to its string representation with a set number of digits?

开发者 https://www.devze.com 2023-01-13 12:20 出处:网络
Pretty much what it says up there. Basically, how开发者_开发技巧 do I get the string produced by

Pretty much what it says up there.

Basically, how开发者_开发技巧 do I get the string produced by

print "%05d" % 100


Maybe I'm misinterpreting the question, but this should work:

my_string = "%05d" % 100


Use str.zfill(width)


This should work too:

`100`.zfill(5)


print('{0:0=5d}'.format(100))
# 00100


    use the 0th positional argument to format
   /  fill character is '0'
  /  / desired width of formatted string
 /  / /
{0:0=5d}

For more, see the docs.


i = 100
str(i).zfill(5)


If you're using Python 3, the str.format method is preferred. It was introduced in Python 2.6. (Alas, my work system is at 2.4 (and I'm not permitted to upgrade), so I can't construct and test an example.)

0

精彩评论

暂无评论...
验证码 换一张
取 消