Removing letters from a string that occur in the previous string

531 Views Asked by At

I need to define a function called remove_letters(str1,str2) which returns a string obtained by removing from string two every letter occurring in str1

So far I have this but It doesn't remove the duplicate letters, it only removes what you put in for it to remove.

def remove_letters(str1,str2):
    str2_list = list(str2)
    for char in str2:
         str2_list.remove()
         return (str2)

Update

I now need to test this function for a variety for strings. When called the code only returns the last result and not the first two. This is my code.

def test_remove_letters():
    string_list = [('sop', 'sen'),('dog', 'god'),('lighter', 'darker')]
    for str1,str2 in string_list:
        print('The original words are', str1, 'and', str2)
        return ('The result is', remove_letters(str1,str2))
2

There are 2 best solutions below

4
Padraic Cunningham On BEST ANSWER
def remove_letters(str1,str2):
    s = set(str1)
    return "".join([char for char in str2 if char not in s])

Or in a loop:

def remove_letters(str1, str2):
    res = ""  
    s = set(str1)
    for char in str2:
        if char not in s: 
            res += char
    return res

Both the loop and the list comprehension have the same logic, we keep the chars in str2 that don't appear in str1.

Using your own code, you need to iterate over str2 and remove any char from str2_list that is in str1 then use join on the list to get a string:

def remove_letters(str1,str2):
    str2_list = list(str2)
    for char in str2:
        if char in str1:
             str2_list.remove(char)
    return "".join(str2_list)
0
AudioBubble On

You can use str.translate and str.maketrans for this:

>>> def remove_letters(str1,str2):
...     return str2.translate(str.maketrans('', '', str1))
...
>>> remove_letters('abc', 'aaabbbccc')
''
>>> remove_letters('abc', 'aaaxbbbycccz')
'xyz'
>>>

If you test this solution with timeit.timeit, you will see it is quite efficient:

>>> from timeit import timeit
>>>
>>> def remove_letters(str1,str2):
...     s = set(str1)
...     return "".join([char for char in str2 if char not in s])
...
>>> timeit("remove_letters('abc', 'aaaxbbbycccz')", "from __main__ import remove_letters")
6.056879016746539
>>>
>>> def remove_letters(str1,str2):
...     return str2.translate(str.maketrans('', '', str1))
...
>>> timeit("remove_letters('abc', 'aaaxbbbycccz')", "from __main__ import remove_letters")
5.283739134443065
>>>