试图了解一些f弦魔术(在f弦中格式化迷你语言)

时间:2019-02-12 17:58:39

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

在对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}<{a}}')。

2 个答案:

答案 0 :(得分:6)

如果您替换某些内容,则可以使输出无效:

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

并阅读String format mini language

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

14444
24444
34444
44444
54444
64444
74444
84444
94444

玩代码是获得其功能的好方法...

答案 1 :(得分: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}<{a}'的作用-在字符串中给定{object}时,它将替换为所述对象。在这种情况下,a的范围是1到9。

那么您只需了解{9:9<9}的功能。答案提供的是the documentation这样的字符串格式化程序:

  

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

x<y部分表示将文本左对齐,宽度为y个空格。对于任何未使用的空间,请用字符x填充。因此,您以{9}作为第一个字符开始,对于其余8个未使用的空格,请以{9}填充。 {9:9<9}就是这样做的。

然后,您应用相同的逻辑,看看每次迭代是如何产生的。

更重要的是,应该注意的是,感觉像“魔术”通常只是缺乏理解。一旦您花时间来消化和理解该过程,它就会变得非常破灭,并为您带来启发。