我怎样才能打印在Python字符串文字花括号字符,也使用它的格式? [英] How can I print literal curly-brace characters in python string and also use .format on it?
本文介绍了我怎样才能打印在Python字符串文字花括号字符,也使用它的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
print x.format(42)
pre>
给我:关键错误:Hello \\
我想打印输出: {Hello} 42
解决方案
您需要将 {{
和}}加倍
:
>>> x ={{Hello}} {0}
>>> print x.format(42)
'{Hello} 42'
以下是相关部分格式字符串语法的Python文档:
< blockquote>
格式字符串包含大括号 {}
所包围的替换字段。任何不包含在大括号中的东西都被认为是文本文本,它被原封不动地复制到输出中。如果您需要在字面文本中包含大括号字符,则可以通过加倍来转义: {{
和}}
。
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}}
.
这篇关于我怎样才能打印在Python字符串文字花括号字符,也使用它的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文