Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I split a string from every word in an array with the split method and then compare it to an array?

I Was wondering how to make a string turn into an array of every word and I came across the .split() function and that split it, but now I want to compare it to another array. How can I do that?

keywords = ["help", "where", "find"]


x = input("How can I help: ")
search = x.split(" ")

for search in keywords:
    if search == keywords:
        print("it looks like you need help with: ", keywords)
    else:
        print("I did not understand")
        print(search, " ", keywords)

I dont really know what to do and any help would be appreciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When using for (iterating variable) in list, you can’t use an already defined variable name for the iterating variable ! this variable takes the value of every word you’re iterating through in your list, one after the other.

Hope this helps ! I tried keeping as much of your own code as simple as possible. If you’re looking for a more optimized solution, use user2390182’s answer.

Feel free to ask further questions if needed.

keywords = ["help", "where", "find"]

x = input("How can I help: ")
search = x.split(" ")

success = False
for word in search : #iterate through each word of variable 'search'
    if word in keywords: #if the word we're currently iterating is in the list 'keywords' :
        print("it looks like you need help with: ", word) #we show the word that triggered the 'if'
        success = True #we take note of the fact we successfully helped the user

if not success: 
    print("I did not understand")
    print(search, " ", keywords)

#the 'if' is located after the loop, outside of its scope.
#this way it only triggers once after the loop instead of triggering with each iteration of the loop

output :

How can I help: i want to find excalibur
it looks like you need help with:  find
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading