【问题标题】:How python interprets fstring width & zero padding?python如何解释fstring宽度和零填充?
【发布时间】: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

【问题讨论】:

    标签: python format f-string


    【解决方案1】:

    你可以这样做:

    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,则在前面填充零,而 {n:>5} 表示在 n 前面填充 5 个空格。 见Python f-string Documentation

    【讨论】:

      【解决方案2】:
      for n in range(1,11):
      sentence = f"The value is {n:02}"
      print(sentence)
      

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

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

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2019-08-12
        • 1970-01-01
        • 2012-04-08
        • 2022-06-13
        • 2013-01-02
        • 2012-09-29
        • 2017-04-13
        相关资源
        最近更新 更多