Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

python - 如何在python字符串中打印文字大括号字符并在其上使用.format?(How can I print literal curly-brace characters in python string and also use .format on it?)

x = " { Hello } {0} "
print x.format(42)

gives me : Key Error: Hello\\

(给我: Key Error: Hello\\)

I want to print the output: {Hello} 42

(我要打印输出: {Hello} 42)

  ask by Schitti translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :

(这是Python文档中有关格式字符串语法的相关部分:)

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

(如果需要在文字文本中包含大括号字符,可以通过加倍{{}}来转义。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...