想要实现字符串居中,可以通过 var:^N 的方式。其中var是想要打印的变量,N是字符串长度。如果N小于var的长度,会打印全部字符串。
>>> hello = "world"
>>>f"{hello:^11}"
' world '
>>>f"{hello:*^11}"
'***world***'
# Extra padding is added to the right
>>>f"{hello:*^10}"
'**world***'
# N shorter than len(hello)
>>>f"{hello:^2}"
'world'