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

时间:2016-12-02 00:59:41

标签: python arrays string 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!"

查看“坏词”的字符串并打印好字符串的最佳方法是什么?

示例...

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!")

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

你可以使用内置函数any()测试是否有任何"坏词"在你的字符串中:

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

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

答案 2 :(得分:2)

您可以使用正则表达式匹配任何不良单词:

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

bad_string是要测试的字符串,is_badTrueFalse,具体取决于bad_string是否包含坏词。