【问题标题】:Why does f"{11: 2d}" not pad to 2 characters?为什么 f"{11: 2d}" 不填充到 2 个字符?
【发布时间】:2019-12-16 22:12:15
【问题描述】:

我正在使用 Ipython 7.0.1Python 3.6.9

我想将数字与格式字符串迷你语言右对齐。我使用 111 作为 1 位和 2 位数字的示例,我想将它们填充到总共 2 个字符。

对于零填充,一切都按预期工作,> 是可选的,因为它是默认值:

In [0]: print(f"{1:02d}\n{11:02d}\n{1:0>2d}\n{11:0>2d}")                                         
01
11
01
11

但是当我想用空格填充它时,只要我将空格留出它也可以工作,以便它默认为空格:

In [1]: print(f"{1:2d}\n{11:2d}\n{1:>2d}\n{11:>2d}")                                             
 1
11
 1
11

但如果我明确输入空格,我会对结果感到惊讶:

In [2]: print(f"{1: 2d}\n{11: 2d}\n{1: >2d}\n{11: >2d}")                                         
 1
 11
 1
11

这是为什么呢?

【问题讨论】:

    标签: python format-string f-string


    【解决方案1】:

    全部在文档中...

    format_spec ::= [[fill]align][sign]...

    如果指定了一个有效的对齐值,它前面可以有一个填充字符

    由于fillsign 都可以是space,这将是不明确的,因此space 作为fill 必须后跟align

    以下是 Python 解释最后一行的方式:

    f"{1: 2d}"    #interpreted as sign therefore (accidentally) same effect  -> " 1"
    f"{11: 2d}"   #interpreted as sign therefore a leading space is inserted -> " 11"
    f"{1: >2d}"   #align is present, pad with ' '                            -> " 1"
    f"{11: >2d}"  #align is present, pad with ' ' but number long enough     -> "11"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多