2

I've seen many solutions of this type of problem but I can't really find one that I'm looking for.

For example:

text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')

for word in user_input:
    if word in text:
        print('Hi')
    else:
        print('Bye')

If the user_input was "hi there", it would give me back

Bye
Bye
Bye
Bye
Bye
Bye
Bye
Bye

How can I check to see if at least one of the words in user_input is in the list (text)?

2
  • 1
    word loops over the characters of the string user_input. Commented Sep 28, 2020 at 7:25
  • 1
    You have to split your user_input into words. Commented Sep 28, 2020 at 7:27

2 Answers 2

6

You can try this:

text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')

for word in user_input.split(" "):
    if word in text:
        print('Hi')
    else:
        print('Bye')

Another Option:

text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')

flag = "Y"
for word in user_input.split(" "):
    if word in text:
        print('Matched String:', word)
    else:
        flag = "N"

if flag == "N":
    print("Unmatched String Exists")
Sign up to request clarification or add additional context in comments.

5 Comments

Split the input into multiple words !
It does work in the fact that it prints 'Hi' when I write a string that is in the list. But it also prints "Bye" for every string NOT in the list
do you want a single "Bye" message?
I'm sorry. I got the answer. This is perfect. I can just do 'pass' for the else thank you!
thanks for your note, please vote-up if you liked the solution !
1

in addition to the others answer, two more options:

  1. using .index()
  2. using a filter in pandas.DataFrame

Option 2 is advantageous as it shows all hits, while option 1 only shows the first hit but is more "pythonic".

Option 1:

text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')

try:
    text.index(user_input)
    print('Hi')
except ValueError:
    print('Bye')

try...except is implemented due to the problem that .index() drops an error in the case that the search string is not in the list.

Option 2:

import pandas as pd
text = ['hi', 'hello', 'hey']
user_input = input('Enter something: ')
df=pd.DataFrame(text)
result=df[df[0]==user_input]
if len(result)>0: 
    print('Hi')
    [print(result[i]) for i in range(len(result))]
else:
    print('Bye')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.