python-3.x 在字符串中搜索多个单词

wwtsj6pe  于 2023-06-25  发布在  Python
关注(0)|答案(3)|浏览(125)

我有一个这样的代码:

string = 'algorithms, c, software design, oop, java, software engineering, data structures, satellite, python, mobile, infrastructure, .net'
enter = input('Enter search: ')

if enter in string:
    print('Yes, it is in there')

当我搜索一个单数单词,如'python'或'oop'等时,这是有效的。
我希望能够在该字符串中搜索多个单词。假设像“algorithms,oop”,它应该返回真值。现在它只显示什么,因为它不能在字符串中找到确切的“algorithms,oop”。但我不想这样,所以如果有人可以帮助,谢谢!

dxxyhpgq

dxxyhpgq1#

我们可以用逗号(,)分割输入句子,然后搜索单个术语。如果没有找到,我们将退出,否则如果所有的都找到了,只需打印'是的,它在那里'

string = 'algorithms, c, software design, oop, java, software engineering, data structures, satellite, python, mobile, infrastructure, .net'
enter = input('Enter search: ')

for word in enter.split(","):
    if word not in string:
        exit()
print('Yes, it is in there')
kninwzqo

kninwzqo2#

添加if/else
片段:

string ='algorithms, c, software design, oop, java, software engineering, data structures, satellite, python, mobile, infrastructure, .net'
enter = input('Enter search: ')

if enter in string:
    print('Yes, it is in there')
else:
    print('No, it is in there')

输出:

Enter search: tkinter
No, it is in there

Enter search: python
Yes, it is in there
mspsb9vt

mspsb9vt3#

试试用这个:

string = 'algorithms, c, software design, oop, java, software engineering, data structures, satellite, python, mobile, infrastructure, .net'

word_dict = {word.strip(): True for word in 
string.split(',')}

enter = input('Enter search terms (comma-separated): ')


search_terms = [term.strip() for term in enter.split(',')]

if all(term in word_dict for term in search_terms):

    print('Yes, all search terms are in there')

else:

    print('Not all search terms are present')

相关问题