Python &引用;语法错误:关键字can';不要成为一种表达;使用模板

Python &引用;语法错误:关键字can';不要成为一种表达;使用模板,python,Python,我正在将字符串命令和字符串列表端口 例如: command = "a b c {iface} d e f" ports = ["abc", "adsd", "12", "13"] 这些字符串被传递给这个函数,我想在这里为命令获取多个字符串,替换 {iface}每个元素位于端口中 def substitute_interface(command, ports): t = string.Template(command) for i in ports: print

我正在将字符串
命令
和字符串列表
端口
例如:

command = "a b c {iface} d e f"
ports = ["abc", "adsd", "12", "13"]
这些字符串被传递给这个函数,我想在这里为命令获取多个字符串,替换
{iface}
每个元素位于
端口中

def substitute_interface(command, ports):
    t = string.Template(command)
    for i in ports:
        print t.substitute({iface}=i)
我在标题中得到错误,我做错了什么?

来自:

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

因此,您需要一个
$
符号,否则模板将无法找到占位符,然后将
iface=p
传递给
替换
函数或字典

>>> 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
发件人:

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

因此,您需要一个
$
符号,否则模板将无法找到占位符,然后将
iface=p
传递给
替换
函数或字典

>>> 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
您有两个错误:

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

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

  • 嗯,他可以,但这与所讨论的错误无关-1感谢可能的方法,我更多的是查看模板,并想知道我在哪里出错:)好吧,他可以,但这与所讨论的错误无关-1感谢可能的方法,我更关注模板,并想知道我在哪里出错:)