如何在 f 字符串中转义花括号? [英] How to escape curly-brackets in f-strings?
问题描述
我有一个字符串,我想在其中使用大括号,但也要利用 f-strings 功能.是否有一些适用于此的语法?
这里有两种方法不起作用.我想包含文字文本 {bar}
作为字符串的一部分.
foo = "test";fstring = f"{foo} {bar}";
NameError: name 'bar' 未定义
fstring = f"{foo} {bar}";
SyntaxError: f-string 表达式部分不能包含反斜杠
想要的结果:
'test {bar}'
看起来这个问题的答案与 如何在字符串中打印文字花括号字符并在其上使用 .format ?,但只有知道 才能知道这一点str.format
使用与 f-string 相同的规则.所以希望这个问题在将 f-string 搜索者与这个答案联系起来方面具有价值.
尽管解析器存在自定义语法错误,相同技巧 与在常规字符串上调用 .format
一样工作.
使用双卷曲:
<预><代码>>>>foo = '测试'>>>f'{foo} {{bar}}''测试 {bar}'I have a string in which I would like curly-brackets, but also take advantage of the f-strings feature. Is there some syntax that works for this?
Here are two ways it does not work. I would like to include the literal text {bar}
as part of the string.
foo = "test"
fstring = f"{foo} {bar}"
NameError: name 'bar' is not defined
fstring = f"{foo} {bar}"
SyntaxError: f-string expression part cannot include a backslash
Desired result:
'test {bar}'
Edit: Looks like this question has the same answer as How can I print literal curly-brace characters in a string and also use .format on it?, but you can only know that if you know that str.format
uses the same rules as the f-string. So hopefully this question has value in tying f-string searchers to this answer.
Although there is a custom syntax error from the parser, the same trick works as for calling .format
on regular strings.
Use double curlies:
>>> foo = 'test'
>>> f'{foo} {{bar}}'
'test {bar}'
It's mentioned in the spec here and the docs here.
这篇关于如何在 f 字符串中转义花括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!