【问题标题】:Trying to understand some f-string magic (formatting mini language in f-strings)试图理解一些 f-string 魔法(在 f-strings 中格式化迷你语言)
【发布时间】:2019-07-06 10:49:36
【问题描述】:

this post 的评论中,有人删除了这行代码:

print("\n".join(f'{a:{a}<{a}}' for a in range(1,10)))
1
22
333
4444
55555
666666
7777777
88888888
999999999

对我来说它看起来很神奇,有人可以向我解释它为什么起作用(更具体地说是f'{a:{a}&lt;{a}}')。

【问题讨论】:

    标签: python python-3.x f-string


    【解决方案1】:

    如果你替换一些东西,你可以消除输出:

    print("\n".join(f'{a:4<5}' for a in range(1,10)))
    

    阅读String format mini language:

    它使用4作为填充符将a的值左对齐在5个空格中:

    14444
    24444
    34444
    44444
    54444
    64444
    74444
    84444
    94444
    

    玩弄代码是了解其功能的好方法...

    【讨论】:

      【解决方案2】:

      如果您将迭代可视化,这非常简单:

      1           # f'{1:1<1}', means start with 1, left align with 1 spaces filled with 1
      22          # f'{2:2<2}', means start with 2, left align with 2 spaces filled with 2
      333         # f'{3:3<3}', means start with 3, left align with 3 spaces filled with 3
      4444        # f'{4:4<4}', means start with 4, left align with 4 spaces filled with 4
      55555       # f'{5:5<5}', means start with 5, left align with 5 spaces filled with 5
      666666      # f'{6:6<6}', means start with 6, left align with 6 spaces filled with 6
      7777777     # f'{7:7<7}', means start with 7, left align with 7 spaces filled with 7
      88888888    # f'{8:8<8}', means start with 8, left align with 8 spaces filled with 8
      999999999   # f'{9:9<9}', means start with 9, left align with 9 spaces filled with 9
      

      您已经知道 f 字符串 f'{a:{a}&lt;{a}' 的作用 - 当在字符串中给出 {object} 时,它将替换为所述对象。在这种情况下,a 的范围是 1 到 9。

      那么你只需要了解{9:9&lt;9} 做了什么。答案提供了the documentation 的字符串格式化程序:

      '&lt;' 强制字段在可用空间内左对齐(这是大多数对象的默认设置)。

      x&lt;y 部分表示将文本左对齐,宽度为y 空格。对于任何未使用的空间,用字符 x 填充它。所以你从{9}作为第一个字符开始,其余8个未使用的空格,用{9}填充。这就是{9:9&lt;9} 所做的。

      然后您应用相同的逻辑并查看每次迭代是如何进行的。

      更重要的是,需要注意的是,什么感觉像“魔术”往往只是缺乏理解。一旦你花时间去消化和理解这个过程,它就会变得非常幻灭,你就会开悟。

      【讨论】:

      • 谢谢,在我的脑海中它会打印出{1:False},尽管它与比较运算符&lt;有关
      • {} 引号内的内容被解释为字符串格式化程序。但是要添加到您的示例中,您也可以 在其中添加计算。例如f'{32:0{"b" if cond else "x"}}' 将根据条件将32 格式化为字节或十六进制。立即评估 {} 内的内容,因此最外层的 {} 单独作为字符串格式化程序,最后评估...如果它是有效格式。
      • 有一天,我可能会真正使用它...谢谢您的精彩解释。
      猜你喜欢
      • 2021-12-16
      • 2023-02-16
      • 2017-04-19
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      相关资源
      最近更新 更多