Python 3.6.5 (default, May 11 2018, 04:00:52)
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>>
39
根据你的提示,我让我的工作功能 . 谢谢 .
def number2binlist(number, leading = 8):
#Convert Binary to 0/1 list array with leading zeros, default 8
bin2dec = int(str(bin(number))[2:])
theformat = "{:0"+str(leading)+"d}"
dec2str = list(theformat.format(bin2dec))
output = [int(z) for z in dec2str]
output.reverse()
return output
16 回答
结果是:
阅读文档中的more information about string formatting using % .
在Python 2中,您可以:
基本上 % 就像
printf
或sprintf
.对于Python 3.可以通过以下方式实现相同的行为:
你可以使用str.zfill:
打印:
在Python 2.6和3.0中,您将使用format()字符串方法:
或使用内置(对于单个数字):
有关新的格式设置功能,请参阅PEP-3101文档 .
打印:
或这个:
print '{0:02d}'.format(1)
在 Python >= 3.6 中,您可以使用以下引入的新f字符串简洁地执行此操作:
它打印名为
val
的变量,其fill值为0
,width为2
.对于您的具体示例,您可以在循环中很好地执行此操作:
打印:
有关f-strings的更多信息,请查看引入它们的PEP 498 .
Pythonic的方法:
这样,如果原始字符串的长度大于string_width,则返回原始字符串 . 例:
结果:
或另一种解决方案
使用格式字符串 - http://docs.python.org/lib/typesseq-strings.html
例如:
使用:
或者使用
math
模块:我是这样做的:
基本上zfill需要你想要添加的前导零的数量,所以很容易取出最大的数字,把它变成一个字符串并获得长度,如下所示:
根据你的提示,我让我的工作功能 . 谢谢 .
结果将是01
如果处理一位或两位数字:
'0'+str(number)[-2:]
或'0{0}'.format(number)[-2:]