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:x<y
部分表示将文本左对齐,宽度为y
个空格。对于任何未使用的空格,请使用字符x
填充它。因此,从{9}
作为第一个字符开始,对于其余8个未使用的空格,用{9}
填充。这就是{9:9<9}
所做的。在然后应用相同的逻辑,看看每个迭代是如何产生的。在
更重要的是,需要注意的是,感觉像“魔术”的往往只是缺乏理解。一旦你花时间去消化和理解这个过程,它就会变得非常幻灭,你就会变得开悟。在
如果您替换一些内容,您可以将输出减半:
阅读String format mini language:
它使用
^{pr2}$4
作为填充符,在5个空格中左对齐a
的值:玩代码是一个很好的方法来获得它的功能。。。在
相关问题 更多 >
编程相关推荐