如何在字符串中打印文字花括号字符并在其上使用 .format? [英] How can I print literal curly-brace characters in a string and also use .format on it?
本文介绍了如何在字符串中打印文字花括号字符并在其上使用 .format?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
x = " { 你好 } {0} "打印(x.格式(42))
给我:关键错误:Hello\
我想打印输出:{Hello} 42
解决方案
你需要把{{
和}}
加倍:
以下是格式字符串语法的 Python 文档的相关部分:
<块引用>格式字符串包含用大括号 {}
包围的替换字段".大括号中未包含的任何内容都被视为文字文本,将原样复制到输出中.如果需要在原义文本中包含大括号字符,可以通过加倍转义:{{
和 }}
.
x = " { Hello } {0} "
print(x.format(42))
gives me : Key Error: Hello\
I want to print the output: {Hello} 42
解决方案
You need to double the {{
and }}
:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
Here's the relevant part of the Python documentation for format string syntax:
Format strings contain "replacement fields" surrounded by curly braces
{}
. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{
and}}
.
这篇关于如何在字符串中打印文字花括号字符并在其上使用 .format?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文