Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string syntax error += operator

Tags:

python

string

I get a syntax error in Python 2.7.3 like so:

[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']

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? 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; it joins a list of strings into a single string, whereas I want to append a string to a list of strings.

like image 361
stewart99 Avatar asked Sep 18 '26 16:09

stewart99


1 Answers

You can't do this. s += 'Orig' is shorthand for s = s + Orig, which is an assignment. For clarity reasons, python does not allow you place assignment statements inside other statements. See the Why can’t I use an assignment in an expression? in the Python FAQ for more details.

like image 85
Joel Cornett Avatar answered Sep 21 '26 07:09

Joel Cornett