【发布时间】:2010-09-28 14:22:30
【问题描述】:
在Python中,int转字符串时如何指定格式?
更准确地说,我希望我的格式添加前导零以获得字符串 具有恒定的长度。例如,如果将常量长度设置为 4:
- 1 将被转换为“0001”
- 12 将被转换为“0012”
- 165 将被转换为“0165”
当整数大于允许给定长度(在我的示例中为 9999)时,我对行为没有任何限制。
如何在Python 中做到这一点?
【问题讨论】:
在Python中,int转字符串时如何指定格式?
更准确地说,我希望我的格式添加前导零以获得字符串 具有恒定的长度。例如,如果将常量长度设置为 4:
当整数大于允许给定长度(在我的示例中为 9999)时,我对行为没有任何限制。
如何在Python 中做到这一点?
【问题讨论】:
"%04d" 其中 4 是恒定长度将按照您的描述进行。
您可以阅读有关字符串格式的内容here.
Python 3 更新:
{:04d} 等效于使用str.format 方法或format 内置函数的字符串。请参阅format specification mini-language 文档。
【讨论】:
您可以使用str 类的zfill 函数。像这样 -
>>> str(165).zfill(4)
'0165'
也可以像其他人建议的那样做%04d 等。但我认为这是更 Pythonic 的方式......
【讨论】:
使用 python3 格式和新的 3.6 f"" 表示法:
>>> i = 5
>>> "{:4n}".format(i)
' 5'
>>> "{:04n}".format(i)
'0005'
>>> f"{i:4n}"
' 5'
>>> f"{i:04n}"
'0005'
【讨论】:
print "%04d" % 1 输出 0001
【讨论】:
使用百分比 (%) 运算符:
>>> number = 1
>>> print("%04d") % number
0001
>>> number = 342
>>> print("%04d") % number
0342
文档是over here
使用% 代替 zfill() 的优点是您可以以更清晰的方式将值解析为字符串:
>>> number = 99
>>> print("My number is %04d to which I can add 1 and get %04d") % (number, number+1)
My number is 0099 to which I can add 1 and get 0100
【讨论】: