2011-11-30 123 views
10

可能重複:
How can I print a literal 「{}」 characters in python string and also use .format on it?如何使用.format()我打印一個字符串,並打印文字大括號在我替換字符串

基本上,我想用.format (),像這樣:

my_string = '{{0}:{1}}'.format('hello', 'bonjour') 

,並讓它匹配:

my_string = '{hello:bonjour}' #this is a string with literal curly brackets 

但是,第一段代碼給了我一個錯誤。

花括號很重要,因爲我使用Python通過基於文本的命令與一段軟件進行通信。我無法控制fosoftware預期的格式,因此我最重要的是理清所有格式。它使用字符串周圍的大括號來確保字符串中的空格被解釋爲單個字符串,而不是多個參數 - 例如,很像您通常在文件路徑中使用引號所做的那樣。我目前使用較老的方法

my_string = '{%s:%s}' % ('hello', 'bonjour') 

這當然有效,但.format()似乎更容易閱讀,當我有五個以上的變量都在一個字符串命令發送,那麼可讀性就成了一個重要的問題。

謝謝!

+1

使用「{ {{0}:{1}}}「(double {{)http://stackoverflow.com/questions/5466451/how-can-i-print-a-literal-characters-in-python-string-and-也使用格式 –

+0

是的,這個問題的重複。 –

回答

20

下面是新樣式:

>>> '{{{0}:{1}}}'.format('hello', 'bonjour') 
'{hello:bonjour}' 

但我想逃逸是有點難以閱讀,所以我更喜歡切換回傳統風格,以避免轉義:

>>> '{%s:%s}' % ('hello', 'bonjour') 
'{hello:bonjour}'