簡體   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