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

5 投票
3 回答
1193 浏览
提问于 2025-04-15 19:40

我有点搞不清楚 字符串模板 是怎么回事:

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 来实现我想要的功能?

3 个回答

1

Python把你名字里的.看作是“访问实例dog的字段old”。你可以试试用_代替,或者把dog变成一个有old字段的对象。

据我记得,只有有效的标识符和.在大括号里是安全的。

[编辑] 这是你链接的页面上的内容:

${identifier} 相当于 $identifier。当有效的标识符字符跟在占位符后面,但不属于占位符时,就需要这样写,比如 "${noun}ification"

还有

"identifier" 必须是一个有效的Python标识符。

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

[编辑2] 看起来标识符并没有像我想的那样被分析。所以你必须在大括号里指定一个简单的有效Python标识符(而且你不能使用字段访问语法),除非你自己实现一个Template class

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)

它会打印出

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))是有效的。

5

根据文档的说明...

$identifier 是一个替代占位符,它对应一个叫做 "identifier" 的映射键。默认情况下,"identifier" 必须是一个有效的 Python 标识符。在 $ 符号后面,第一个不是标识符的字符会结束这个占位符的定义。

句号是一个不是标识符的字符,而大括号只是用来把标识符和旁边的非标识符文本分开的。

撰写回答