簡體   English   中英

Python:如何將int轉換為具有一定位數的字符串表示形式?

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

上面說的差不多。

基本上,我如何獲得由

print "%05d" % 100

也許我誤解了這個問題,但這應該可行:

my_string = "%05d" % 100

使用str.zfill(width)

這也應該工作:

`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}

有關更多信息,請參閱docs

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

如果您使用的是Python 3,則首選str.format方法。 它是在Python 2.6中引入的。 (A,我的工作系統為2.4(並且我不允許升級),所以我無法構建和測試示例。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM