python 如何解释 f 字符串宽度和零填充?

How python interprets fstring width & zero padding?

我是 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 如何解释宽度和精度? 为什么示例 2 最后一个循环 没有用零填充计算?

如果我没记错的话,示例 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

你可以这样做:

for n in range(1,11):
    n = f'{n:0>2}'
    sentence = f"The value is {n:>5}"
    print(sentence)

{n:0>2}表示如果n的数字小于2,则在前面填充0,而{n:>5}表示在n前面填充5个空格。 参见 Python f-string Documentation

for n in range(1,11):
sentence = f"The value is {n:02}"
print(sentence)

您可以将 {n:02} 更改为 {n:03} 或其他以检查差异。

{n:0x} 打印十六进制格式。