我想将 a 中的“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'
我怎样才能将 a 中的“the”的数量减少 2。如果不能这样做,那么有没有更简单的方法来执行此操作?
请您参考如下方法:
b = "the"
a = b * 5
print a
a = a[:-2*len(b)]
print a
# returns: thethethe
我不是在做减法(你不能真正用字符串做),我是从 a 的末尾删除两倍长度的 b,忽略它的实际值。
