Home > Back-end >  Delete a string if matching with a list [duplicate]
Delete a string if matching with a list [duplicate]

Time:09-21

I want to recognize if the words from a list are in an input string, and if so remove that word.

I have tried:

words = ["youtube","search youtube","play music"]
Inp = "search youtube Rockstar"

if words in Inp:
   Inp = Inp.replace(words,"")

And the wanted output is:

Inp = "Rockstar"

CodePudding user response:

Use a for loop as so:

words = ["youtube","search youtube","play music"]
Inp = "search youtube Rockstar"

for word in words:
  if word in Inp:
    Inp = inp.replace(word, '')
  else:
    pass

print(Inp)

CodePudding user response:

You have to loop through the words list and replace each word.

for word in words:
    Inp = Inp.replace(word, '')

If there's overlap between the elements of words, such as youtube and search youtube, you need to put the longer one first. Otherwise, when youtube is removed, it won't find search youtube to replace it. So make it:

words = ["search youtube","youtube","play music"]

If you can't change words like this, you can sort them when looping:

for word in sorted(words, key=len, reverse=True):

CodePudding user response:

It's a bit complected to remove space separated strings from a string. You have to do some hacks to achive this.

Steps:

  1. Firstly you have to generate an unique list of words that you want to remove
  2. Remove filtered words from the string
  3. Create a new list of words from previously generated string
  4. Finally join the list to remove unnecessary spaces

Code:

import re


def remove_matching_string(my_string, words):
    # generate an unique list of words that we want to remove
    removal_list = list(set(sum([word.split() for word in words], [])))

    # remove strings from removal list
    for word in removal_list:
        insensitive_str = re.compile(re.escape(word), re.IGNORECASE)
        my_string = insensitive_str.sub('', my_string)

    # split string after apply removal list
    my_string = my_string.split()

    # concat string to remove unnecessary space between words
    final_string = ' '.join(s for s in my_string if s)

    # return the final string
    return final_string


words = ["youtube","search youtube","play music"]
Inp = "Search youtube Rockstar Play Music On Youtube   PlAy MusIc Now"

final_string = remove_matching_string(Inp, words)
print(final_string)

Output:

Rockstar On Now
  • Related