[小白提问]string.Template里面可以赋为二级字典的值吗

小白提问,请大神指点。

我希望能把values[‘test2’][‘name’]的值传进string当中。但总是失败。
跑出来总是把整个values[‘test2’]传进去了,”.name”变成了字符串。
是语法写错了吗,求指点。

values = {'var': 'foo','test':'11','test2':{'name':'qqq','class':'aaa'}}
t = string.Template("""
Variable        : $var
Escape          : $$
Variable in text: $test2.name
""")
print('TEMPLATE:', t.substitute(values))

结果:
TEMPLATE:
Variable : foo
Escape : $
Variable in text: {‘name’: ‘qqq’, ‘class’: ‘aaa’}.name

讨论数量: 6

也许你需要这样子做

file

3周前 评论
Helen2022 (楼主) 3周前
Helen2022 (楼主) 3周前

file

结果是: NameError: name 'Template' is not defined

这个是需要导入的类库吗?

3周前 评论
sinmu 3周前
Jason990420

It cannot be done by using string.Template.

I build one for it, not test and not sure if anything failed.

import re


class Dict(dict):

    def __init__(self, d={}):
        super().__init__()
        for key, value in d.items():
            self[key] = Dict(value) if type(value) is dict else value

    def __getattr__(self, key):
        if key in self:
            return self[key]
        raise AttributeError(key) #Set proper exception, not KeyError

    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


class Template():

    def __init__(self, template):
        self.template = template

    def repl(self, match):
        text = match.group(1)
        return str(eval("self.values."+text)) if text else "$"

    def format(self, values):
        self.values = Dict(values)
        return re.sub(r"\$(.*?)\$", self.repl, self.template, re.MULTILINE)


template = Template("""
Variable        : $var$
Escape          : $$
Variable in text: $test2.name$
""".strip())

values = {'var': 'foo','test':'11','test2':{'name':'qqq','class':'aaa'}}
print(template.format(values))
Variable        : foo
Escape          : $
Variable in text: qqq
3周前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!