[英]python string syntax error += operator
I get a syntax error in Python 2.7.3 like so: 我在Python 2.7.3中遇到语法错误,如下所示:
[s += 'Orig' for s in strs]
File "<stdin>", line 1
[s += 'Orig' for s in strs]
^
SyntaxError: invalid syntax
where strs is just a list of strings, like ['a', 'b', 'c', 'd']
其中strs只是一个字符串列表,如
['a', 'b', 'c', 'd']
if I change the code to: 如果我将代码更改为:
[s + 'Orig' for s in strs]
Then it works: 然后它工作:
['aOrig', 'bOrig', 'cOrig', 'dOrig']
What's the reason behind this? 这背后的原因是什么? Is it because the s in the list comprehension is not mutable?
是因为列表理解中的s不可变吗? But it should be a temporary object that is discarded later anyway, so why not?
但它应该是一个暂时的对象,无论如何都会被丢弃,为什么不呢?
Also, what is the most efficient way to do what I want to do? 另外,做我想做的最有效的方法是什么? I looked at another link: http://www.skymind.com/~ocrow/python_string/ and tried to use join, but join does not do what I want;
我查看了另一个链接: http : //www.skymind.com/~ocrow/python_string/并尝试使用join,但是join并没有做我想要的事情; it joins a list of strings into a single string, whereas I want to append a string to a list of strings.
它将字符串列表连接成一个字符串,而我想将一个字符串附加到字符串列表中。
Assignment in Python (including +=
) is a statement, not an expression. Python中的赋值(包括
+=
)是一个语句,而不是表达式。 You can only use expressions in a list comprehension. 您只能在列表推导中使用表达式。
What does your example with +
not do that you want it to do? 你的例子
+
你没有那样做你想要它做什么?
You can't do this. 你不能这样做。
s += 'Orig'
is shorthand for s = s + Orig
, which is an assignment. s += 'Orig'
是s = s + Orig
简写,这是一个赋值。 For clarity reasons, python does not allow you place assignment statements inside other statements. 为清楚起见,python不允许您将赋值语句放在其他语句中。 See the Why can't I use an assignment in an expression?
请参阅为什么我不能在表达式中使用赋值? in the Python FAQ for more details.
在Python FAQ中了解更多详细信息。
Well, you could do 好吧,你可以做到
strs = [s+'Orig' for s in strs]
or 要么
strs = map(lambda s: s+'Orig', strs)
I find the list comprehension (the first one) easier to read. 我发现列表理解(第一个)更容易阅读。
You cant use it as an expression. 你不能用它作为表达。 Only through an assignment in a statement can the (+=) symbol be used.
只有通过语句中的赋值才能使用(+ =)符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.