2010-02-24 76 views
4

我不能完全弄清楚發生了什麼事情與string templatesPython中的字符串模板:什麼是合法字符?

t = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working') 
print t.safe_substitute({'dog.old': 'old dog', 'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% NOT'}) 

此打印:

cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working 

我認爲括號處理任意的字符串。什麼字符被允許在大括號,並有任何方式我可以繼承Template做我想要的?

+0

+1:鏈接文檔。 -1:沒有真正閱讀鏈接的文檔。 – 2010-02-24 15:04:34

+0

WTF?我確實讀過它,我對Python和它的文檔樣式相當陌生(相對於javadoc而言,事情相當冗長)。謝謝你跳過我,因爲錯過了一個小細節。 – 2010-02-24 15:08:55

+0

所有的編程都是小細節。事實上,你連接到文檔都是超過許多關於SO的問題。 – 2010-02-24 15:12:03

回答

4

從文檔...

$標識符名稱替換佔位符匹配「標識符」的一個映射鍵。默認情況下,「標識符」必須拼寫一個Python標識符。 $字符後的第一個非標識符字符終止此佔位符規範。

該句點是一個非標識符字符,而花括號僅用於將標識符與相鄰的非標識符文本分開。

1

Python將您的名字中的.解釋爲「訪問實例dog的字段old」。請嘗試使用_,或使dog成爲old的對象。

AFAIR,只有有效標識符和.在支架之間是安全的。

[編輯]這是在頁面上,你鏈接到:

${identifier}相當於$identifier。當有效標識符字符跟隨佔位符但不是佔位符的一部分時是必需的,例如"${noun}ification"

"identifier"必須闡明一個Python標識符。

這意味着:它必須是一個有效的標識符。

[編輯2]似乎沒有像我想的那樣分析標識符。因此,除非您創建自己的Template class實現,否則必須在大括號中指定一個簡單的有效Python標識符(並且不能使用字段存取器語法)。

+0

好的,謝謝!這是記錄在哪裏,並有任何方法來覆蓋它? – 2010-02-24 14:50:36

+1

要重寫,可以派生模板的子類以自定義佔位符語法。 – 2010-02-24 14:56:06

+1

這是不正確的,並沒有在文檔中提到。否則,'print t.safe_substitute({'dog':{'old':'old dog'}},'trick':{'new':'new tricks'},'why':'OH WHY','not ':'@#%@#%NOT'})'會起作用,但事實並非如此。 – MikeWyatt 2010-02-24 14:57:02

3

啊哈,我想這個實驗:

from string import Template 
import uuid 

class MyTemplate(Template): 
    idpattern = r'[a-z][_a-z0-9]*(\.[a-z][_a-z0-9]*)*' 

t1 = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working') 
t2 = MyTemplate('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working') 
map1 = {'dog.old': 'old dog', 
    'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% NOT'} 
map2 = {'dog': {'old': 'old dog'}, 
     'tricks': {'new': 'new tricks'}, 'why': 'OH WHY', 'not': '@#%@#% NOT'} 
print t1.safe_substitute(map1) 
print t1.safe_substitute(map2) 
print t2.safe_substitute(map1) 
print t2.safe_substitute(map2) 

它打印

cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working 
cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working 
cannot teach an old dog new tricks. OH WHY is this @#%@#% NOT working 
cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working 

所以第三個(print t2.safe_substitute(map1))的作品。