Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

string - Fixed width number formatting python 3

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...