2016-07-27 25 views
0

使用Python的string.Template類 - 如何在包含空格的字典中使用$ {}作爲字段?Python string.Template:替換包含空格的字段

E.g.

t = string.Template("hello ${some field}") 
d = { "some field": "world" } 
print(t.substitute(d)) # Returns "invalid placeholder in string" 

編輯:這是最接近我能得到,需要提醒的是,所有的變量都需要包裝在一個括號(否則所有空格分隔的單詞會被匹配)。

class MyTemplate(string.Template): 
    delimiter = '$' 
    idpattern = '[_a-z][\s_a-z0-9]*' 

t = MyTemplate("${foo foo} world ${bar}") 
s = t.substitute({ "foo foo": "hello", "bar": "goodbye" }) 
# hello world goodbye 

回答

0

以防萬一這可能有助於別人。在Python 3,你可以使用format_map

t = "hello {some field}" 
d = { "some field": "world" } 
print(t.format_map(d)) 

# hello world 
+0

啊,這看起來不錯 - 它是唯一的Python 3?我可能應該提到Python 2.7x支持的必要性 – funseiki

+0

您可以簡單地使用'str'的​​'.format'方法:'print('hello {some field}'。format(** d))' –

0

從文檔它說,我們可以使用模板選項

https://docs.python.org/dev/library/string.html#template-strings

import string 

class MyTemplate(string.Template): 
    delimiter = '%' 
    idpattern = '[a-z]+ [a-z]+' 

t = MyTemplate('%% %with_underscore %notunderscored') 
d = { 'with_underscore':'replaced', 
     'notunderscored':'not replaced', 
     } 

print t.safe_substitute(d) 
+0

'有點困惑 - 你期望得到什麼輸出?我剛剛運行了這段代碼,並得到了「%%with_underscore不被替換」 – funseiki

+0

這是一個非常接近我想要的近似值,只要所有變量都包含在{}中(如果您使用此類或類似的方法更新答案,將其標記爲正確):idpattern ='[_a-z] [_ \ sa-z0-9] *' – funseiki