字符串占位符替换
字符串替换
from string import Template class PortTemplate(Template): delimiter = "@@" res = PortTemplate('@@{lico_port1}').substitute({'lico_port1':2}) print(res)
进阶使用(一)
from string import Template from collections import defaultdict res = (i for i in range(100)) def zero(): return next(res) class PortTemplate(Template): delimiter = "@@" if __name__ == '__main__': dd = defaultdict(zero) res1 = PortTemplate('@@{lico_port1} @@{lico_port2}').substitute(dd) print(res1) print(dd.items())
进阶使用 (二)
from string import Template class A(dict): def __init__(self): self.port_list = [] self.unused = (i for i in range(100)) def __getitem__(self, name): port = next(self.unused) self.port_list.append({name: port}) return port class PortTemplate(Template): delimiter = "@@" if __name__ == '__main__': a= A() res1 = PortTemplate('@@{lico_port1} @@{lico_port2} @@{lico_port3}').substitute(a) print(res1) print(a.port_list)