'How to find whole word (with space) from array using Python?

I have an array that is given below. I want to compare users response with this array.

array = ['finance', 'healthcare', 'information technology', 'government', 'textile', 'petroleum']

Here is my code.

 if str(user_response) in str(array):
    for j in range(array_length):
        if str(user_response) == str(array[j]):
          some code
 else:
     print("give valid answer")

If the users response would be 'information technology', then it is working fine. But if the users response would be only technology, then it also is consider as an answer. It has to print the else message when user will give response like technology.

So, how can I match whole word 'information technology' from the array, instead of only 'technology'?



Solution 1:[1]

You have too many str() casts all around, making the initial if a substring search.

Try

array = ['finance', 'healthcare', 'information technology', 'government', 'textile', 'petroleum']

user_response = str(...)  # wherever you get the input from

# If you don't cast `array` to a string, 
# Python will just try to find the string in the list; 
# otherwise it does a substring search.

if user_response in array:
   # ...
else:
   print("Give valid answer")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKX