【问题标题】:How to check a string for elements in an array in python 3.4如何在python 3.4中检查数组中元素的字符串
【发布时间】:2016-12-02 00:59:41
【问题描述】:

假设我有以下变量...

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

【问题讨论】:

    标签: python arrays string python-3.4


    【解决方案1】:

    这很简单,遍历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
    

    【讨论】:

      【解决方案2】:

      您可以使用内置函数any() 来测试您的字符串中是否有任何“坏词”:

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

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

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 2020-11-12
          • 2021-10-15
          • 2015-05-08
          • 1970-01-01
          • 2022-07-30
          • 2016-08-27
          • 1970-01-01
          • 2013-10-31
          • 2011-12-23
          相关资源
          最近更新 更多