添加前导零 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21620602/
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
Add leading Zero Python
提问by Evan Gervais
I was wondering if someone could help me add a leading zero to this existing string when the digits are sings (eg 1-9). Here is the string:
我想知道当数字是唱歌时(例如 1-9),是否有人可以帮我在这个现有的字符串中添加一个前导零。这是字符串:
str(int(length)/1440/60)
采纳答案by thefourtheye
You can use the builtin str.zfillmethod, like this
您可以使用内置str.zfill方法,如下所示
my_string = "1"
print my_string.zfill(2) # Prints 01
my_string = "1000"
print my_string.zfill(2) # Prints 1000
From the docs,
从文档中,
Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than or equal to len(s).
返回在长度和宽度的字符串中用零填充的数字字符串。正确处理符号前缀。如果宽度小于或等于 len(s),则返回原始字符串。
So, if the actual string's length is more than the width specified (parameter passed to zfill) the string is returned as it is.
因此,如果实际字符串的长度大于指定的宽度(传递给 的参数zfill),则字符串将按原样返回。
回答by James Sapam
I hope this is the easiest way:
我希望这是最简单的方法:
>>> for i in range(1,15):
... print '%0.2d' % i
...
01
02
03
04
05
06
07
08
09
10
11
12
13
14
>>>
回答by falsetru
Using formator str.format, you don't need to convert the number to str:
使用format或str.format,您不需要将数字转换为str:
>>> format(1, '02')
'01'
>>> format(100, '02')
'100'
>>> '{:02}'.format(1)
'01'
>>> '{:02}'.format(100)
'100'
According to the str.formatdocumentation:
根据str.format文档:
This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting ...
这种字符串格式化方法是 Python 3 中的新标准,应该优先于 % 格式化...

