首页 > 解决方案 > 转义 f 字符串中的字符

问题描述

我遇到了以下问题f-string

>>> a='hello'

# how to print '{hello}' ?

>>> f'{{a}}'
'{a}'

>>> f'\{{a}\}'
  File "<stdin>", line 1
SyntaxError: f-string: single '}' is not allowed

# doing it without f-strings
>>> '{' + a + '}'
'{hello}'

如何在 fstring 中转义字符?

标签: pythonpython-3.xf-string

解决方案


你需要三重括号:

f'{{{a}}}'

两个外部{}s “转义”并评估为{...},然后内部{}用于格式化(或者至少我是这样解释的)。


推荐阅读