繁体   English   中英

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

[英]String templates in Python: what are legal characters?

我无法弄清楚字符串模板发生了什么:

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子类Template我想要的内容?

从文档......

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

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

啊哈,我试过这个实验:

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) )工作。

Python解释了. 在你的名字中“访问实例dog old字段”。 尝试使用_或者使dog成为old字段的对象。

AFAIR,只有有效的标识符和. 大括号之间是安全的。

[编辑]它在您链接到的页面上:

${identifier}相当于$identifier 当有效标识符字符跟随占位符但不是占位符的一部分时,例如"${noun}ification"

"identifier"必须拼写Python标识符。

这意味着:它必须是有效的标识符。

[EDIT2]似乎没有像我想象的那样分析标识符。 因此,除非您创建自己的Template类实现,否则必须在大括号中指定一个简单的有效Python标识符(并且不能使用字段访问器语法)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM