简体   繁体   English

f 字符串中的 Escaping 字符

[英]Escaping chars in f-string

I have run into the following issue with the f-string :我遇到了f-string的以下问题:

>>> a='hello'

# how to print '{hello}' ?

>>> f'{{a}}'
'{a}'

>>> f'\{{a}\}'
  File "<stdin>", line 1
SyntaxError: f-string: single '}' is not allowed

# doing it without f-strings
>>> '{' + a + '}'
'{hello}'

How do I escape chars in an fstring?如何在 fstring 中转义字符?

You need triple braces:你需要三重括号:

f'{{{a}}}'

The two outer {} s "escape" and evaluate to {...} , then the inner {} is used for formatting (or at least that's how I interpret it).两个外部{} “转义”并评估为{...} ,然后内部{}用于格式化(或者至少我是这样解释的)。

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

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