Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模板字符串python 2.5错误_Python - Fatal编程技术网

模板字符串python 2.5错误

模板字符串python 2.5错误,python,Python,我得到的错误是 #!/usr/bin/python from string import Template s = Template('$x, go home $x') s.substitute(x='lee') print s 我想要的结果是:lee,回家lee您需要查看substitute的返回值。它将为您提供执行了替换的字符串 <string.Template object at 0x81abdcc> 模板对象本身(s)不会更改。这使您能够对同一模板对象执行多个替

我得到的错误是

#!/usr/bin/python

from string import Template

s = Template('$x, go home $x')
s.substitute(x='lee')

print s


我想要的结果是:lee,回家lee

您需要查看
substitute
的返回值。它将为您提供执行了替换的字符串

<string.Template object at 0x81abdcc>

模板对象本身(
s
)不会更改。这使您能够对同一模板对象执行多个替换。

您需要查看
substitute
的返回值。它将为您提供执行了替换的字符串

<string.Template object at 0x81abdcc>
print s.substitute(x='lee')

模板对象本身(
s
)不会更改。这使您能够对同一模板对象执行多个替换。

您不会得到错误:您得到的正是您想要的——模板本身。为了达到你想要的结果

print s.substitute(x='lee')
print s.substitute(x='lee')

模板和字符串一样,都是不可更改的对象:对模板(或字符串)调用的任何方法都无法更改该模板——它只能生成一个单独的结果,供您使用。当然,这适用于
.substitute
方法。你调用它,但忽略结果,然后打印模板——毫无疑问,你希望模板本身会有某种改变,但这不是它的工作原理。

你没有得到错误:你得到的正是你想要的——模板本身。为了达到你想要的结果

print s.substitute(x='lee')
模板和字符串一样,都是不可更改的对象:对模板(或字符串)调用的任何方法都无法更改该模板——它只能生成一个单独的结果,供您使用。当然,这适用于
.substitute
方法。您正在调用它,但忽略结果,然后打印模板——毫无疑问,您希望模板本身以某种方式被修改,但这不是它的工作方式