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 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.

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

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

>Solution :

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")
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