我似乎无法找到正确的格式化规范前面的零在Python中 [英] I cannot seem to find the correct formatting spec for preceding zeroes in python

查看:151
本文介绍了我似乎无法找到正确的格式化规范前面的零在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆