简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM