If you want an exact match, use word boundaries with re.search:
import re
mylist = ["hello there", "Watermelons are delicious", "What is the colour of my shirt"]
mylist[:] = [s for s in mylist if not re.search(r"\bis the colour\b",s)])
Output:
['hello there', 'Watermelons are delicious']
mylist[:]
will mean you mutate the original list, using word boundaries means is the colours
etc.. won't be matched which may or may not be the desired behaviour.
If you want to get the indexe(s) of the string(s) that contains the substring use enumerate
keeping the ind if re.search(r"\bis the colour\b",s)
:
print([ind for ind, s in enumerate(mylist) if re.search(r"\bis the colour\b",s)])
Output:
[2]
If you only want the first match if there may be more than one:
ind = next((s for s in mylist f re.search(r"\bis the colour\b",s)),None)
if ind:
print(ind)
If you want to remove from both lists together, zip, check for the substring match and remove if there is a match:
mylist = ["red is the color of my shirt", "hello there", "foo", "Watermelons are delicious",
"What is the color of my shirt", "blue is the color of my shirt", "foobar"]
otherlist = ["0", "1", "2", "3", "4", "5", "6"]
for s1, s2 in zip(mylist, otherlist):
if re.search(r"\bis the color\b", s1):
mylist.remove(s1)
otherlist.remove(s2)
print(mylist)
print(otherlist)
Output:
['hello there', 'foo', 'Watermelons are delicious', 'foobar']
['1', '2', '3', '6']