Casa > C > Como Resolver Typeerror: Tipo(S) De Operando Não Suportado(S) Para -: 'Str' E 'Str' Em Python

Como resolver TypeError: tipo(s) de operando não suportado(s) para -: 'str' e 'str' em Python

OK. As chances são que esses "operandos" deveriam ter sido convertidos em tipos numéricos (como int) em algum momento. Nesse caso, TL;DR e leia a resposta de Tony Flury, que explica isso completamente, melhor do que eu poderia.

No entanto, ainda há uma chance de que você estivesse bem ciente de que estas eram strings (digamos, a e b), e você queria subtraí-las de qualquer forma. Nesse caso, vamos assumir que o resultado desejado era o mais razoável, o que, para mim, é remover toda ocorrência de b de a.

Se você achar essa suposição muito perigosa, então isso automaticamente explica porque não há um operador padrão para subtrair strings em Python. (à parte, claro, dos fatos que isso levaria a resultados confusos, como '150'-'5' == '10' e que esse tipo de subtração não é simétrica à adição, o que significa que a-b+b dificilmente voltaria a a, a menos que b seja encontrado apenas uma vez, no final de a).

A boa notícia é que existe um método de string que pode alcançar isso facilmente, chamado de substituição, então, chamá-lo em uma string para substituir um substrato com o vazio, faria o truque. Por exemplo, para remover "bad" da string "este é um mau exemplo", pode-se escrever

  1. ' este é um mau exemplo'.replace('bad', '') 

However, if you find that using ‘-’ operator on strings is critical for the readability of your code, you can always create a new string subclass that implements this behavior.

Then, having started with arithmetic operations on strings, why not division, too? Not too apparent what we would expect it to do, though…

Let’s say, that when called with a string as second operand, it splits the first one by that, or, with an int (say n) as a second operand, it ‘divides’ the string to n, same-sized segments.

What about the remainder? Well, let’s implement that, too. A mod, it is :-)

  1. # Some preparation stuff for the example to work in both Py2 & 3... 
  2. from six import PY2, integer_types 
  3. if PY2: 
  4. from types import StringType 
  5. else: 
  6. StringType = str 
  7.  
  8.  
  9. class Thong(StringType): 
  10. """ A string ... with extras """ 
  11.  
  12. def __sub__(self, other): 
  13. """ Remove from self all occurrences of 'other' """ 
  14. return self.replace(other, '') 
  15.  
  16. def __div__(self, other): 
  17. """ String division: 
  18. if 'other' is a string, split self by that string 
  19. if 'other' is a number, slice self in that number of same-sized  
  20. segments  
  21. regretfully, not symmetric with multiplication """ 
  22.  
  23. if isinstance(other, (integer_types, float)): 
  24. seglen = int(len(self)/other) 
  25. return [self[n-seglen:n] for n in range(seglen, len(self)+1, seglen)] 
  26.  
  27. # else: # possibly isinstance(other, (string_types)) 
  28. return self.split(other) 
  29.  
  30. def __mod__(self, other): 
  31. """ String modulo: 
  32. Return what remained from string division with 'other' """ 
  33. # if isinstance(other, (integer_types, float)):  
  34. # let it raise for incompatible types 
  35. seglen = int(len(self)/other) 
  36. return self[other*seglen:] 
  37.  
  38. # examples 
  39. if __name__ == '__main__': 
  40. t = Thong("this is a test string") 
  41. print(t - "is") 
  42. print(t / 5) 
  43. print(t % 5) 
  44. # note that we also get -= as a bonus :-) 
  45. t-="a " 
  46. print(t) 

OK, OK, this is the kind of meaningless operator overloading that Linus used to criticize on C++ …

But when programming purely for fun, I guess it doesn’t hurt :-)

De Rawden Adeyemo

Existe alguma versão hack do Clash of Clans disponível na internet? :: O que você acha do telefone XZ2 Premium?