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

Categories

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

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

1 Answer

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}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...