Python中的字符串模板:什么是合法字符?

Jas*_*n S 5 python string templates

我不太清楚字符串模板到底是怎么回事:

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'})
Run Code Online (Sandbox Code Playgroud)

打印:

cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working
Run Code Online (Sandbox Code Playgroud)

我以为花括号可以处理任意字符串。花括号中可以包含哪些字符,我可以通过任何方法继承Template我想要的东西吗?

Mik*_*att 5

从文档中...

$ identifier命名与映射键“ identifier”匹配的替换占位符。默认情况下,“标识符”必须拼写Python标识符。$字符后的第一个非标识符字符终止此占位符规范。

句点是一个非标识符字符,大括号仅用于将标识符与相邻的非标识符文本分开。


Jas*_*n S 5

啊哈,我试过这个实验:

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)
Run Code Online (Sandbox Code Playgroud)

哪个打印

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
Run Code Online (Sandbox Code Playgroud)

所以第三个 ( print t2.safe_substitute(map1)) 有效。