用大括号字符填充 f 字符串

问题描述

在 Python 中,我们可以这样填充 f 字符串:

>>> f"{' hello ':#^80}"
'#################################### hello #####################################'

如何用 ' hello ' 字符填充 { 字符串?

解决方法

为大括号本身使用转义序列:

>>> f"{' hello ':\x7b^80}"
'{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ hello {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{'
,

你可以这样做:

f"{' hello ':{chr(123)}^80}"

要确定“{”的值为 123,您可以运行 ord("{") 返回 123

输出

'{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ hello {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{'