简体   繁体   English

格式化字符串文字语法

[英]Formatted string literals grammar

In Python official document 2.4.3. Python官方文档2.4.3中。 Formatted string literals the following grammar is defined: 格式化字符串文字定义了以下语法:

f_string          ::=  (literal_char | "{{" | "}}" | replacement_field)*

Can someone explain why there are two curly braces here?有人可以解释为什么这里有两个花括号吗?

This is explained immediately below the grammar definition:这在语法定义下面立即解释:

The parts of the string outside curly braces are treated literally, except that any doubled curly braces '{{' or '}}' are replaced with the corresponding single curly brace.大括号外的字符串部分按字面意思处理,除了任何双大括号 '{{' 或 '}}' 被相应的单大括号替换。

This is so that you can "escape" the braces if you want literal braces to appear.这样一来,如果您希望出现文字大括号,就可以“转义”大括号。 As an example:举个例子:

>>> print(f"braces look like {{this}}")
braces look like {this}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM