首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

检查列表中的单词是否在另一个列表Python的字符串中

在Python中,我们可以使用以下代码来检查一个列表中的单词是否在另一个字符串中:

代码语言:txt
复制
def check_words_in_string(word_list, string):
    for word in word_list:
        if word in string:
            print(f"{word} is present in the string.")
        else:
            print(f"{word} is not present in the string.")

# 示例用法
word_list = ["apple", "banana", "orange"]
string = "I like to eat apples and bananas."
check_words_in_string(word_list, string)

这段代码定义了一个名为check_words_in_string的函数,它接受两个参数:word_liststringword_list是要检查的单词列表,string是要检查的字符串。

函数使用for循环遍历word_list中的每个单词。对于每个单词,它使用in关键字检查它是否在字符串string中。如果单词存在于字符串中,它会打印出"{word} is present in the string.",否则打印"{word} is not present in the string."。

在示例用法中,我们定义了一个word_list列表和一个string字符串,并调用check_words_in_string函数来检查word_list中的单词是否在string中。

请注意,这只是一个简单的示例,你可以根据实际需求进行修改和扩展。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券