我似乎无法找到正确的格式化规范前面的零在Python中 [英] I cannot seem to find the correct formatting spec for preceding zeroes in python
问题描述
john = 2
johnmod = format(john,' (f)
print(johnmod)
我回到了2.00,但是,添加前面的零的格式规范是什么?我想输出为0002,我发现与谷歌唯一的规范是使用%04d,这是行不通的。如果有问题,我在Windows上运行Python 3.3。
b
$ b
首先使用 string formatting minilanguage ,使用你的尝试方法,第一个零表示填充,第四个表示宽度:
>>>格式(2,04)
'0002'
另外,格式minilanguage:
>>> '{0:04}'。format(2)
'0002'
在:
之后, 0
表示用零填充, 4
表示宽度为四。
>>> two = 2
>>>最后,<$ c $
$ b >>> $ c> str.zfill
方法是为这个定制的: str(2).zfill(4)
'0002'
When adding decimal places, it's as simple as
john = 2
johnmod = format(john, '.2f')
print(johnmod)
and I get 2.00 back, as expected. But, what's the format spec for adding preceding zeros? I would like for the output to be 0002, and the only spec I've found with Google for that is using %04d, which did not work. If it matters, I am running Python 3.3 on windows.
Several Pythonic ways to do this,:
First using the string formatting minilanguage, using your attempted method, first zero means the fill, the 4 means to which width:
>>> format(2, "04")
'0002'
Also, the format minilanguage:
>>> '{0:04}'.format(2)
'0002'
the specification comes after the :
, and the 0
means fill with zeros and the 4
means a width of four.
New in Python 3.6 are formatted string literals:
>>> two = 2
>>> f'{two:04}'
'0002'
Finally, the str.zfill
method is custom made for this:
>>> str(2).zfill(4)
'0002'
这篇关于我似乎无法找到正确的格式化规范前面的零在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!