2013-03-22 57 views
1

如何將{symbol in string?如何在Python格式字符串中包含符號「{」?

我的字符串

str2="call_function(Macro, {0});\n \{ \t int n;\n".format("value") 

,我發現了錯誤:

ValueError: unmatched '{' in format 

我躲過了十符號,並沒有逃避也都試過了。在這兩種情況下,我都會遇到同樣的錯誤。

回答

5

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


+1

[如果您需要在文字文本中的大括號字符,它可以通過加倍轉義:{{和}}](http://docs.python.org /2/library/string.html#formatspec) – jedwards 2013-03-22 09:05:44

+0

嘿,謝謝你的提示。完美的作品。我需要知道的任何其他逃脫技巧? – Abhishek 2013-03-22 09:10:26

+0

@Abhishek - [任何不包含在大括號中的東西都被認爲是文本文本,它會被原樣複製到輸出中。](http://docs.python.org/2/library/string.html#formatstrings)。無論如何,我認爲通過文檔咀嚼自己會是有益的。 – root 2013-03-22 09:13:08

相關問題