Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - 显示数字的前导零(Display number with leading zeros)

Given:

(鉴于:)

a = 1
b = 10
c = 100

How do I display a leading zero for all numbers with less than two digits?

(如何为少于两位的所有数字显示前导零?)

That is,

(那是,)

01
10
100
  ask by ashchristopher translate from so

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

1 Reply

0 votes
by (71.8m points)

In Python 2 you can do:

(在Python 2中,您可以执行以下操作:)

print "%02d" % (1,)

Basically % is like printf or sprintf .

(基本上就像printfsprintf 。)


For Python 3.+ the same behavior can be achieved with:

(对于Python 3. +,可以通过以下方式实现相同的行为:)

print("{:02d}".format(1))

For Python 3.6+ the same behavior can be achieved with f-strings:

(对于Python 3.6+,可以使用f字符串实现相同的行为:)

print(f"{1:02d}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...