尝试理解一些fstring的魔力(在fstring中格式化mini语言)

2024-05-17 05:04:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

对我来说,它就像魔法,有人能解释一下为什么它能起作用(更具体地说f'{a:{a}<{a}}')。在


Tags: 代码infor魔法评论rangethispost
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-string f'{a:{a}<{a}'的作用了——当在字符串中给定一个{object}时,它将替换为所述对象。在本例中,a的范围是1到9。在

那么你需要了解的就是{9:9<9}是做什么的。答案提供了一个字符串格式化程序the documentation

'<' Forces the field to be left-aligned within the available space (this is the default for most objects).

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

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

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

如果您替换一些内容,您可以将输出减半:

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

阅读String format mini language

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

^{pr2}$

玩代码是一个很好的方法来获得它的功能。。。在

相关问题 更多 >