简体   繁体   中英

How do I print words that are the same in two sentences in python?

5a. Prompt the user to enter 2 sentences, called sen1 and sen2

5b. Print all the words that are in both sentences

sen1 = (input("Input first sentence: ").split(" "))
sen2 = (input("input second sentence: ").split(" "))
print(list(set(sen1).intersection(sen2)))

Sorry I misunderstand your question at first. This is the corrected version. (PS: I did not consider the sentence initial situation, you may use lower() function to correct the code yourself.

def main():
    sen1 = input('Please enter sentence 1:')
    sen2 = input('Please enter sentence 2:')
    wordlist1 = a1.split()
    wordlist2 = a2.split()   
    for i in wordlist1:
        if i in wordlist2:
            print(i)
        else:
            print('No common word.')
main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM