0

在对这篇文章的评论中,有人删除了这行代码:

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}}')。

4

2 回答 2

7

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

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

并阅读字符串格式的迷你语言

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

14444
24444
34444
44444
54444
64444
74444
84444
94444

玩弄代码是获得它的作用的好方法......

于 2019-02-12T18:05:14.253 回答
3

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

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}的。它是一个字符串格式化程序,作为答案提供的文档

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

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

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

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

于 2019-02-12T18:30:44.890 回答