Johhhbb
Johhhbb

Reputation: 1

How to remove all occurences of a string?

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')

Upvotes: 0

Views: 436

Answers (1)

Renaud
Renaud

Reputation: 2819

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

Upvotes: 2

Related Questions