Python中的减法运算符
我想把字符串中“the”这个词的数量减少2个。但是这段代码好像不管用。我不明白为什么乘法运算符可以用,但减法运算符却不行。
b = "the"
a = b * 5
print a
a -= (b * 2)
print a
输出
the
the the the the the
Traceback (most recent call last):
a -= (b * 2)
TypeError: unsupported operand type(s) for -=: 'str' and 'str'
我该怎么把字符串中“the”的数量减少2个。如果这样做不行,那有没有更简单的方法来实现这个呢?
6 个回答
2
这要看你是想从开头还是结尾去掉元素,你可以使用数组的子集功能:
>>> a[2*len("the"):]
'thethethe'
>>> a[:-(2*len("the"))]
'thethethe'
4
b = "the"
a = b * 5
print a
a = a[:-2*len(b)]
print a
# returns: thethethe
我并不是在做减法(其实字符串是不能直接减的),我只是从a的末尾去掉两倍于b长度的部分,而不管b的实际内容是什么。
3
为了减少你单词中“the”的数量2次,可以试试用replace这个方法:
b = "the"
a = b * 5
print a
>>> "thethethethethe"
a = a.replace(b, "", 2) # or a.replace(b*2, "", 1) if you want to remove "thethe" from the string
print a
>>> "thethethe"
如果你想从后面开始去掉“the”,可以使用rsplit()。
b = "the"
a = "theAtheBthethe"
a = "".join(a.rsplit("the", 2)) # or "".join(a.rsplit("thethe", 1)) if you want to remove "theth" of the string
print a
>>> "theAtheB"
正如这里所描述的,*这个符号在字符串(还有unicode、列表、元组、字节数组、缓冲区、xrange类型)中是可以用的,b * 5
会返回5个b拼在一起的结果。