在Python中,如何在将int转换为字符串时指定格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3813735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python, how to specify a format when converting int to string?
提问by PierrOz
In Python, how do I specify a format when converting int to string?
在Python中,将int转换为字符串时如何指定格式?
More precisely, I want my format to add leading zeros to have a string with constant length. For example, if the constant length is set to 4:
更准确地说,我希望我的格式添加前导零以获得长度恒定的字符串。例如,如果常量长度设置为 4:
- 1 would be converted into "0001"
- 12 would be converted into "0012"
- 165 would be converted into "0165"
- 1 将转换为“0001”
- 12 将转换为“0012”
- 165 将转换为“0165”
I have no constraint on the behaviour when the integer is greater than what can allow the given length (9999 in my example).
当整数大于给定长度(在我的示例中为 9999)时,我对行为没有限制。
How can I do that in Python?
我怎样才能在Python 中做到这一点?
采纳答案by nmichaels
回答by Srikar Appalaraju
You could use the zfillfunction of strclass. Like so -
你可以使用类的zfill功能str。像这样——
>>> str(165).zfill(4)
'0165'
One could also do %04detc. like the others have suggested. But I thought this is more pythonic way of doing this...
一个人也可以%04d像其他人建议的那样做等。但我认为这是更pythonic的方式来做到这一点......
回答by mac
Use the percentage (%) operator:
使用百分比 ( %) 运算符:
>>> number = 1
>>> print("%04d") % number
0001
>>> number = 342
>>> print("%04d") % number
0342
Documentation is over here
文档在这里
The advantage in using %instead of zfill() is that you parse values into a string in a more legible way:
使用%而不是 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
回答by Powertieke
回答by MortenB
With python3 format notation:
使用 python3 格式表示法:
>>> i = 5
>>> "{:4n}".format(i)
' 5'
>>> "{:04n}".format(i)
'0005'

