2011-11-17 190 views
1

我想从一个2减少“the”字的数量。但是这段代码似乎没有运行。我不明白为什么乘法运算符能够工作,但减法运算符不能。减法运算符python

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' 

我怎样才能减少“了”的一个数除以2。如果这不能这样可以做到,那么有没有一种更简单的方法执行此?

回答

3

为了减少你字“的”由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" 

如果你想删除 “的” 从年底开始,用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" 

作为described here,*运算符由字符串(以及Unicode,列表,元组,字节阵列,缓冲区,xrange类型)支持,b * 5返回连接的b个副本。

+0

这串内将“删除”字符的第一个出现次数,所以如果你有“theAtheBthethe”,你不会得到你可能等待... – eumiro

+1

a.replace实际上并没有改变'a'。你需要做一个= a.replace(...) – Spacedman

+0

@eumiro:对,我编辑了我的答案来处理这种可能性 –

3
b = "the" 
a = b * 5 
print a 

a = a[:-2*len(b)] 
print a 

# returns: thethethe 

我不是从其减去(你不能真正做到用绳子),我从a末除去两次b长度,忽视了其真正的价值。

2

取决于如果你想砍他们关闭的开始或结束时,您可以使用数组子集:

>>> a[2*len("the"):] 
'thethethe' 
>>> a[:-(2*len("the"))] 
'thethethe' 
1
a = a.rpartition(b * 2)[0] 

应该这样做,从右侧切割。如果您在a中没有'thethe'的任何示例,它将返回空字符串''。如果您有多个由其他字符分隔的多个'the',它将不起作用。为此,您可以使用两次a.rpartition(b)[0]。如果您想从左侧剪切,请使用a.partition(b * 2)[2]

为什么不减去工作?使用加法和乘法是使用字符串的一个便利功能。减法(或除法)str s的语义没有为Python定义,所以你不能以这种方式使用它。

2

没有为字符串中的情况下,减法运算符不支持,但你可以简单地添加一个:

>>> class MyStr(str): 
    def __init__(self, val): 
     return str.__init__(self, val) 
    def __sub__(self, other): 
     if self.count(other) > 0: 
      return self.replace(other, '', 1) 
     else: 
      return self 

,这将在下面的方式工作:

>>> a = MyStr('thethethethethe') 
>>> b = a - 'the' 
>>> a 
'thethethethethe' 
>>> b 
'thethethethe' 
>>> b = a - 2 * 'the' 
>>> b 
'thethethe' 

关于a - 2 * 'the'操作你应该知道,这不是“”从“删除了两次'字符串”,而是“”从“(第一次乘以”the“通过2,然后从a减去)。

这是你所期望的吗?

1

加运算符工作,因为“+”连接而减去不对字符串操作。您可以尝试使用一些正则表达式,如:

import re 

s="the"*5 
expr="the" 

print s 

# s -= 2 
print "".join(re.findall(expr,s)[:-2]) 

# s -=3 
print "".join(re.findall(expr,s)[:-3])