How to escape f-strings in python 3.6? [duplicate]

拥有回忆 提交于 2019-11-27 17:06:47

问题


This question already has an answer here:

  • How can I print literal curly-brace characters in python string and also use .format on it? 12 answers

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


回答1:


Although there is a custom syntax error from the parser, the same trick works as for regular strings.

Use double curlies:

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

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



来源:https://stackoverflow.com/questions/42521230/how-to-escape-f-strings-in-python-3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!