固定宽度数字格式化python 3 [英] Fixed width number formatting python 3

查看:589
本文介绍了固定宽度数字格式化python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得一个整数在Python 3.2中使用format属性填充0的固定宽度?
示例:
$ b $ pre $
print('{0:3}'。format(a )}

给出了'1'而不是'001'我想要在python 2.x中,I知道这可以使用

  print%03d%number。

我检查了python 3的字符串文档,但是无法得到这个。

< a href =http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language =noreferrer> http://docs.python.org/release/ 3.2 / library / string.html#format-specification-mini-language

谢谢。

解决方案

前缀的宽度为 0

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

另外,你不需要Python的最新版本中的位置标记(不知道哪个,但是至少2.7和3.1):

 >>>'{:03}'。fo rmat(1)
'001'


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.

解决方案

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'

这篇关于固定宽度数字格式化python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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