0

How can I change this function to remove all occurrences of a given letter from a string?

from test import testEqual

def remove(substr,theStr):
    index = theStr.find(substr)
    if index < 0: # substr doesn't exist in theStr
        return theStr
    return_str = theStr[:index] + theStr[index+len(substr):]
    return return_str

testEqual(remove('an', 'banana'), 'bana')
testEqual(remove('cyc', 'bicycle'), 'bile')
testEqual(remove('iss', 'Mississippi'), 'Missippi')
testEqual(remove('egg', 'bicycle'), 'bicycle')
Johhhbb
  • 1
  • 1
  • 4
  • Your code shows True for every equality tests, what it the problem ? – azro Nov 16 '20 at 21:41
  • It seems like you could simply just keep running `remove` on the result recursively until `(theStr.find(substr) < 0) == True`. Is there some reason why that solution wouldn't work for you? – Random Davis Nov 16 '20 at 21:41
  • The function that was originally written to remove the first occurrence of a string from another string so it will return true still – Johhhbb Nov 16 '20 at 22:02
  • Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – anishtain4 Nov 16 '20 at 22:05
  • Check the answers from this question: basically, your fonction is a re.sub: import re ; re.sub("an", "", "banana) -> https://stackoverflow.com/questions/38773379/simplest-python-equivalent-to-rs-gsub – Gildas Nov 17 '20 at 07:33

1 Answers1

2

If you want to remove all occurrence replace() can be a good choice:

def remove(substr,theStr):
     return_str=theStr.replace(substr, '' )
     return return_str
Renaud
  • 2,709
  • 2
  • 9
  • 24
  • Use `str.replace(substr, "", n)` where ***n*** is used to indicate the number of times you want it to occur. – Deneb Nov 16 '20 at 21:47
  • Yes, it's a builtin method for string https://docs.python.org/2/library/string.html – Renaud Nov 16 '20 at 22:51