Search code examples
pythonlistfor-looplist-comprehension

How to remove a list of substrings from a list of strings


I can find lots of advice re: removing a list of substrings from a string but very little / none on removing a list of substrings from a list of strings.

My data is as such :

List 1 : [Op 18 TC 16, TC 20, OP 15 TC 80]

List 2 : [Op 18, , OP 15]

Expected result : a final list containing : [TC 16, TC 20, TC 80]

I am aware that I will need to account for spaces and such and the answer may well be obvious / staring me in the face but I just cant seem to crack this one.

I have tried for loop within a for loop but end up with the obvious multitude of values in the final list and I have tried a list comprehension that I thought would work but it had no affect.

If I need to improve the question please tell me, but please help as I am stuck on this one


Solution

  • Try this:

    lst1 = ['Op 18 TC 16', 'TC 20', 'OP 15 TC 80']
    lst2 = ['Op 18', 'OP 15']
    
    result = []
    for s1 in lst1:
        tmp = s1
        for s2 in lst2:
            tmp = tmp.replace(s2, '')
        result.append(tmp.strip())
    

    Here is the result

    >>> result
    ['TC 16', 'TC 20', 'TC 80']