做a = b + a的更好方法吗? [英] Any better way for doing a = b + a?

查看:30
本文介绍了做a = b + a的更好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PyCharm,我有这样的声明:

I'm using PyCharm and I have this statement:

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

PyCharm 突出显示最后一行:

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'

但是 'foobar' 不是我想要的;'barfoo' 是.

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

那么,这个增强的任务是什么?有没有更合适的方法来做到这一点,还是我应该忽略 PyCharm 的警告?

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

推荐答案

请忽略 PyCharm,它很迟钝.当操作数不能只是交换时,这句话显然不适用.

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

提示适用于数字操作数,因为 a + b 产生与 b + a 相同的结果,但对于字符串加法不是可交换的,PyCharm 应该避免它.

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)

但我不会打扰,真的.

这篇关于做a = b + a的更好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆