如何在python 3.6中转义f字符串? [英] How to escape f-strings in python 3.6?
问题描述
我有一个想要大括号的字符串,但也可以利用f字符串功能.是否有一些适用于此的语法?
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?
有两种方法不起作用.我想将文字文本"{bar}
"作为字符串的一部分.
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:名称"bar"未定义
NameError: name 'bar' is not defined
fstring = f"{foo} \{bar\}"
SyntaxError:f字符串表达式部分不能包含反斜杠
SyntaxError: f-string expression part cannot include a backslash
所需结果:
'test {bar}'
Looks like this question has the same answer as How can I print literal curly-brace characters in python string and also use .format on it?, but you can only know that if you know that the format function uses the same rules as the f-string. So hopefully this question has value in tying f-string searchers to this answer.
推荐答案
尽管解析器存在自定义语法错误,但相同技巧的作用类似于在常规字符串上调用.format
.
Although there is a custom syntax error from the parser, the same trick works as for calling .format
on regular strings.
使用双头冰壶:
>>> foo = 'test'
>>> f'{foo} {{bar}}'
'test {bar}'
这篇关于如何在python 3.6中转义f字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!