Question

I am trying to write part of a script that will evaluate whether or not any of two (or more) given characters are present in a string. It seems that the logical OR operator is always true in my IF/IN sentence. Any ideas?

#!/usr/bin/python
mylist = ['abc', 'def']
for mystring in mylist:
    if 'a' in mystring:
        print mystring
    if 'a' or 'b' in mystring:
        print mystring

prints:
abc
abc
def
Was it helpful?

Solution

The issue in your code is that 'a' always evaluates to True and you are saying: "is 'a' True or is 'b' in mystring True".

def is_chars_in_strings(strings, chars):
    answer = []
    for string in strings:
        a = False
        for char in chars:
            if char in string:
                a = True
                break
        if not a:
            answer.append(string)
    return answer

print (is_chars_in_strings(['abc', 'def'], 'ab'))

OTHER TIPS

The statement: if 'a' or 'b' in mystring is the same as: if ('a') or ('b' in mystring), resulting in True for all cases, as if 'a': is always true.

You can solve this problem by using list comprehensions:

 if any([c in mystring for c in 'ab']):
   ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top