Fixed width number formatting python 3

为君一笑 提交于 2019-12-18 01:18:08

问题


How do I get an integer to fill 0's to a fixed width in python 3.2 using the format attribute? Example:

a = 1
print('{0:3}'.format(a)} 

gives ' 1' instead of '001' I want. In python 2.x, I know that this can be done using

print "%03d" % number. 

I checked the python 3 string documentation but wasn't able to get this.

http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language

Thanks.


回答1:


Prefix the width with a 0:

>>> '{0:03}'.format(1)
'001'

Also, you don't need the place-marker in recent versions of Python (not sure which, but at least 2.7 and 3.1):

>>> '{:03}'.format(1)
'001'



回答2:


There is built-in string method .zfill for filling 0-s:

>>> str(42).zfill(5)
'00042'
>>> str(42).zfill(2)
'42'



回答3:


Better:

number=12
print(f'number is equal to {number:03d}')


来源:https://stackoverflow.com/questions/6869999/fixed-width-number-formatting-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!