2016-12-29 59 views

回答

1

根據documentation,佔位符值的默認正則表達式是[_a-z][_a-z0-9]*,這意味着/字符不被允許。如果你想允許這樣做,你應該繼承Template並重新定義idpattern表達:

from string import Template 

class MyTemplate(Template): 
    idpattern = r"[_a-z][_a-z0-9/]*" # allowing forward slash 

key_val = {'a/b/c': 1} 
ans = MyTemplate('val of ${a/b/c}').substitute(key_val) 

演示:

In [8]: from string import Template 

In [9]: class MyTemplate(Template): 
    ...:  idpattern = r"[_a-z][_a-z0-9/]*" # allowing forward slash 
    ...:  

In [10]: key_val = {'a/b/c': 1} 

In [11]: ans = MyTemplate('val of ${a/b/c}').substitute(key_val) 

In [12]: ans 
Out[12]: 'val of 1' 
+0

太好了!謝謝。 – Sandeep