1

对于一个函数,我传入一个字符串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)

我得到标题中的错误,我做错了什么?

4

2 回答 2

3

你有两个错误:

  1. 正如错误消息所说,关键字参数必须是标识符,而是{iface}一个表达式(特别是包含 的当前值的集合iface)。名称周围的大括号iface是标记,用于告诉替换引擎那里有要替换的内容。要传递该占位符的值,只需提供 key iface,最好是通过编写t.substitute(iface=i)
  2. string.Template不支持该语法,它想要$iface(或者${iface}如果前者不能使用,但这种情况下你可以使用$iface)。str.format支持这种语法,但显然你不想使用它。
于 2013-06-27T10:37:03.043 回答
2

来自文档

$identifier 命名一个与“identifier”映射键匹配的替换占位符

所以你需要一个$标志,否则模板将无法找到占位符,然后传递iface = psubstitute函数或字典。

>>> 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 f
a b c adsd d e f
a b c 12 d e f
a 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 f
a b c adsd d e f
a b c 12 d e f
a b c 13 d e f
于 2013-06-27T10:28:58.260 回答