使用模板“ SyntaxError:关键字不能是表达式”

我要向一个函数传递一个字符串command和一个字符串列表,ports 例如:


command = "a b c {iface} d e f"

ports = ["abc", "adsd", "12", "13"]

这些都传递给此函数,在这里我想获取多个命令字符串,用{iface}其中的每个元素替换 ports


def substitute_interface(command, ports):

    t = string.Template(command)

    for i in ports:

        print t.substitute({iface}=i)

标题出现错误,我在做什么错?


互换的青春
浏览 183回答 2
2回答

开心每一天1111

从文档:$ identifier命名与映射键“ identifier”匹配的替换占位符因此,您需要一个$符号,否则模板将无法找到占位符,然后传递iface = p给substitute函数或字典。>>> command = "a b c ${iface} d e f"  #note the `$`>>> t = Template(command)>>> for p in ports:    print t.substitute(iface = p) # now use `iface= p` not `{iface}`...     a b c abc d e fa b c adsd d e fa b c 12 d e fa b c 13 d e f无需任何修改,您就可以将此字符串"a b c {iface} d e f"与结合使用str.format:for p in ports:    print command.format(iface = p)...     a b c abc d e fa b c adsd d e fa b c 12 d e fa b c 13 d e f
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python