Python how to evaluate if one of two substrings in string using OR operator [duplicate]

StackOverflow https://stackoverflow.com/questions/23423661

  •  14-07-2023
  •  | 
  •  

문제

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
도움이 되었습니까?

해결책

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'))

다른 팁

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']):
   ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top