如何在 python 3.6 中转义 f 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42521230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:50:17  来源:igfitidea点击:

How to escape f-strings in python 3.6?

pythonpython-3.6f-string

提问by JDAnders

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?

我有一个字符串,我想要花括号,但也可以利用 f-strings 功能。是否有一些适用于此的语法?

Here are two ways it does not work. I would like to include the literal text "{bar}" as part of the string.

这里有两种方法不起作用。我想将文字“ {bar}”作为字符串的一部分。

foo = "test"
fstring = f"{foo} {bar}"

NameError: name 'bar' is not defined

NameError: 名称 'bar' 未定义

fstring = f"{foo} \{bar\}"

SyntaxError: f-string expression part cannot include a backslash

SyntaxError: f-string 表达式部分不能包含反斜杠

Desired result:

想要的结果:

'test {bar}'

Edit: 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.

编辑:看起来这个问题与如何在 python 字符串中打印文字花括号字符并在其上使用 .format具有相同的答案,但只有知道format函数使用与f-string相同的规则才能知道。所以希望这个问题在将 f-string 搜索者与这个答案联系起来方面具有价值。

回答by wim

Although there is a custom syntax error from the parser, the same trickworks as for calling .formaton regular strings.

尽管解析器存在自定义语法错误,但调用.format常规字符串相同的技巧也有效。

Use double curlies:

使用双卷曲:

>>> foo = 'test'
>>> f'{foo} {{bar}}'
'test {bar}'

It's mentioned in the spec hereand the docs here.

它在规格中提到这里和文档在这里