Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any better way for doing a = b + a?

I'm using PyCharm and I have this statement:

a = 'foo'
b = 'bar'
a = b + a

and PyCharm highlights the last line saying that:

Assignment can be replaced with augmented assignment

First I thought there might be something like this but ended up with error:

a += b # 'foobar'
a =+ b # TypeError: bad operand type for unary +: 'str'

But 'foobar' is not what I want; 'barfoo' is.

So, what is this augmented assignment? Is there a more proper way to do this or should I ignore PyCharm's warning?

like image 711
Taxellool Avatar asked Feb 01 '15 11:02

Taxellool


People also ask

Is it worth getting a BA?

Earning your bachelor's degree also increases the likelihood that you will be considered by future employers for career advancement opportunities. An undergraduate degree is also an obvious prerequisite for earning a master's degree or PhD, if you aspire to pursue a graduate education in the future.


1 Answers

Just ignore PyCharm, it is being obtuse. The remark clearly doesn't apply when the operands cannot just be swapped.

The hint works for numeric operands because a + b produces the same result as b + a, but for strings addition is not commutative and PyCharm should just keep out of it.

If you really want to avoid the message, you could use string formatting:

a = '{}{}'.format(b, a)

but I'd not bother, really.

like image 125
Martijn Pieters Avatar answered Sep 24 '22 22:09

Martijn Pieters