如何在 python 3.4 中检查数组中元素的字符串

How to check a string for elements in an array in python 3.4

假设我有以下变量...

bad_words = ['bad0', 'bad1', 'bad2']
bad_string = "This string has bad1 in it."
bad_string2 = "This string is abcbad0xyz."
good_string = "This string is good!"

查看 'bad words' 字符串并仅打印出正确字符串的最佳方法是什么?

示例...

def check_words(string):
    bad_words = ['bad0', 'bad1', 'bad2']
    #this is where I need help... 
    #Return False if string contains any of the words in bad words
    #Return True if string does not contain bad words.


bad_string = "This string has bad1 in it."
good_string = "This string is good!"

#call the check_words method by sending one of the strings
valid = check_words(bad_string)    #I want this to return False

if valid:
    print("Good string!")
else:
    print("Bad string!")

#or...
valid = check_words(good_string)    #I want this to return True

if valid:
    print("Good string!")
else:
    print("Bad string!")

这非常简单,遍历 bad_words 并检查单词是否在 string 中,如果在 return False 中。在我们检查了所有 bad_words 之后,我们可以 return True 安全。

def check_words(string):
    bad_words = ['bad0', 'bad1', 'bad2']
    for word in bad_words:
        if word in string:
            return False
    return True

您可以使用内置函数 any() 来测试您的字符串中是否有 "bad words":

def check_words(string, words):
  return any(word in string for word in words)

string 是测试字符串,words 是坏词列表。这通过测试 words 列表中的任何单词是否在您的字符串中来实现。 any() 函数然后根据您的条件 returns 一个布尔值。

您可以使用正则表达式来匹配任何坏词:

is_bad = re.search('|'.join(bad_words), bad_string) != None

bad_string是要测试的字符串,is_badTrueFalse,取决于bad_string是否有坏词。