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

时间:2021-03-26 09:19:37

标签: python python-3.x f-string

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

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

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

你可以这样做:

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

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

输出

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