【发布时间】:2020-12-23 06:25:12
【问题描述】:
我是python的新手。
我一直在搞清楚fstring 的工作原理
示例 1
for n in range(1,11):
sentence = f"The value is {n:{n:1}}"
print(sentence)
输出:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
The value is 6
The value is 7
The value is 8
The value is 9
The value is 10
示例 2
for n in range(1,11):
sentence = f"The value is {n:{n:02}}"
print(sentence)
输出:
The value is 1
The value is 02
The value is 003
The value is 0004
The value is 00005
The value is 000006
The value is 0000007
The value is 00000008
The value is 000000009
The value is 10
示例 3
for n in range(1,11):
sentence = f"The value is {n:{n:03}}"
print(sentence)
输出:
The value is 1
The value is 02
The value is 003
The value is 0004
The value is 00005
The value is 000006
The value is 0000007
The value is 00000008
The value is 000000009
The value is 0000000010
我真正想知道的是
fstring 如何解释宽度和精度?
为什么 example 2 last loop 没有用零填充计算?
如果我没记错的话,示例 1 的输出被解释为宽度。 示例 2 和示例 3 是填充零。
另外, 我如何编写代码来获得这样的零填充宽度? 需要输出:
The value is 01
The value is 02
The value is 03
The value is 04
The value is 05
The value is 06
The value is 07
The value is 08
The value is 09
The value is 10
【问题讨论】: