如果您将迭代可视化,这非常简单:
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} 所做的。
然后您应用相同的逻辑并查看每次迭代是如何进行的。
更重要的是,需要注意的是,什么感觉像“魔术”往往只是缺乏理解。一旦你花时间去消化和理解这个过程,它就会变得非常幻灭,你就会开悟。