Any better way for doing a = b + a?(做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的更好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:做a = b + a的更好方法吗?
基础教程推荐
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
