Python 前置的加等于运算符
Python plus-equals operator that prepends
是否有 Python +=
运算符的变体,它是前置而不是追加?
即x += 'text'
,而不是 x+'text'
,'text'+x
。
编辑:
我正在尝试在程序的一部分中创建命令行,但我一直收到错误消息:
Traceback (most recent call last):
File "./main.py", line 15, in <module>
a[0] = 'control/'+a[0]
TypeError: 'str' object does not support item assignment
代码片段:
a = a.split()
# Command Line
if (a[0][0:1] == '!') and (len(a[0]) > 1):
a = a[0][1:] # remove evoker
if a == 'quit': break
else:
try:
a[0] += 'control/'+a[0]
subprocess.call(a)
except:
print("That is not a valid command.")
不,没有前置运算符。
这可能是您正在寻找的解决方案。
如果您使用自己的 class,您可以定义非常特殊的增量操作来覆盖 __iadd__
:
class My_str(str):
def __iadd__(self, other):
return other+self
ms = My_str('hello')
ms += 'world'
print(ms)
生产
worldhello
因此,对于列表中的此类元素,您可以执行类似
的操作
>>> l = [My_str(i) for i in range(5)]
>>> l[1] += 'text'
>>> l
['0', 'text1', '2', '3', '4']
欢迎所有评论。
是否有 Python +=
运算符的变体,它是前置而不是追加?
即x += 'text'
,而不是 x+'text'
,'text'+x
。
编辑:
我正在尝试在程序的一部分中创建命令行,但我一直收到错误消息:
Traceback (most recent call last):
File "./main.py", line 15, in <module>
a[0] = 'control/'+a[0]
TypeError: 'str' object does not support item assignment
代码片段:
a = a.split()
# Command Line
if (a[0][0:1] == '!') and (len(a[0]) > 1):
a = a[0][1:] # remove evoker
if a == 'quit': break
else:
try:
a[0] += 'control/'+a[0]
subprocess.call(a)
except:
print("That is not a valid command.")
不,没有前置运算符。
这可能是您正在寻找的解决方案。
如果您使用自己的 class,您可以定义非常特殊的增量操作来覆盖 __iadd__
:
class My_str(str):
def __iadd__(self, other):
return other+self
ms = My_str('hello')
ms += 'world'
print(ms)
生产
worldhello
因此,对于列表中的此类元素,您可以执行类似
的操作>>> l = [My_str(i) for i in range(5)]
>>> l[1] += 'text'
>>> l
['0', 'text1', '2', '3', '4']
欢迎所有评论。