gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:07:53 25 4
gpt4 key购买 nike

假设我有以下变量...

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

最佳答案

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

关于python - 如何在 python 3.4 中检查数组中元素的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40923078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com