带大括号和函数的 f 字符串

f-string with curly brace and function

我搜索了现有答案。我找到了打印花括号的答案,但它们也不包括在 f 字符串中执行函数。标记为重复的那个没有解决我的问题。

我尝试打印的部分字符串是从一个函数中解析出来的。我的字符串的静态部分包括花括号。我可以使用旧样式执行该功能,但我希望使用新的 f 弦来执行此功能。最终字符串应如下所示:

test{aloha}

旧风格作品:

>>> print('test{%s}'%(aloha()))
'test{aloha}'

f-string - 正如预期的那样,没有打印大括号:

>>> print(f"test{(aloha())}")
'testaloha'

带双卷曲的 f 字符串 - 函数未执行:

>>> print(f"test{{(aloha())}}")
"test{(xor('label'.encode(), 13).decode())}"

f 字符串转义花括号 - 语法错误:

>>> print(f"test\{{(aloha())}\}")
"SyntaxError: f-string: single '}' is not allowed"

f-string 仅转义左花括号 - 不执行:

>>> print(f"test\{{(aloha())}}")
"test\{(xor('label'.encode(), 13).decode())}"

我是不是太过分了?

编辑:将原来执行的函数缩短为“aloha()”,但在我编辑时人们已经给出了可行的答案。他们的答案是正确的。

这样:

f"test{{{(xor('label'.encode(), 13).decode())}}}"

你需要三卷发。每个双花括号构成一个转义花括号:

>>> f"{{{1}}}"
'{1}'