2010-02-24 135 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))的作品。