pog*_*ogo 11 string formatting string-formatting fixed-width python-3.x
如何使用format属性获取一个整数,以便在python 3.2中将0填充到固定宽度?例:
a = 1
print('{0:3}'.format(a)}
Run Code Online (Sandbox Code Playgroud)
给出'1'代替我想要的'001'.在python 2.x中,我知道这可以使用
print "%03d" % number.
Run Code Online (Sandbox Code Playgroud)
我检查了python 3字符串文档,但无法得到它.
http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language
谢谢.
Mar*_*tos 47
使用以下前缀加宽宽度0:
>>> '{0:03}'.format(1)
'001'
Run Code Online (Sandbox Code Playgroud)
此外,您不需要最近版本的Python中的位置标记(不确定哪个,但至少2.7和3.1):
>>> '{:03}'.format(1)
'001'
Run Code Online (Sandbox Code Playgroud)
有内置的字符串方法.zfill用于填充 0-s:
>>> str(42).zfill(5)
'00042'
>>> str(42).zfill(2)
'42'
Run Code Online (Sandbox Code Playgroud)