Aero Aero - 1 year ago 188
Python Question

Detect if string has a substring and delete element in Python

I'm just trying to detect whether a string has a substring in it so I can remove it. So I'm detecting words from posts and storing them into m. Then I want to loop through them to detect keywords. I can't get it to work though. The values 4-6 are just letters and numbers.

m = re.findall('some values from 4-6', submission.selftext)
for x in m:
i = 0
if any("memory" or "hard" or "drive" in s for s in x):
del m[i]
i += 1

But it seems that it doesn't work when I try to search x. It skips that if statement entirely no matter what m is.

Answer Source

You have two problems:

if any("memory" or "hard" or "drive" in s for s in x):

should be:

if any("memory" in s or "hard" in s or "drive" in s for s in x):

And you are skipping some is:

The best way to fix this is by using a list comprehension:

m = [x for x in m if not ("memory" in x or "hard" in x or "drive" in x)]

You don't need to iterate through x, since each s would be a character, and would never contain the string memory

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download