5

So I am doing a for loop of a list. Every single string, I want to .find, but instead of .find one item for a string, I want to check that string for anything in my list.

For example.

checkfor = ['this','that','or the other'] 

then do

string.find(checkfor) or something, so I'd like to do this:

if email.find(anything in my checkforlist) == -1:
    do action
1
  • 1
    Are you trying to find the positions of everything in that list, or are you trying to check if anything in that list is contained in your string? Commented Jul 17, 2016 at 1:43

4 Answers 4

3

If you just want to know if at least one value in the list exists in the string then a simple way to do that would be:

any(email.find(check) > -1 for check in checkfor)

If you want to check that all of them exist in the string then do

all(email.find(check) > -1 for check in checkfor)

Or if you want the exact values that did have a match in the string you can do:

matches = [match for match in checkfor if email.find(match) > -1]

I would prefer to use:

check in email

over

email.find(check) > -1

but I guess it can depend on your use case (the above examples would probably look better with the in operator).

Depending on your case, you may prefer to use regular expressions, but I won't get into that here.

Sign up to request clarification or add additional context in comments.

Comments

1

I want to check that string for anything in my list

Python has in for that.

for s in checkfor:
    if s in email:
        # do action 

Comments

0

You could try using list comprehension to accomplish this.

occurrences = [i for i, x in enumerate(email) if x =='this']

Comments

0

Use the in clause:

If checkfor not in email:
    do_some_thing()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.