Search code examples
pythonenumerate

How do i find a word from user input in another variable?


This is my code:

a = ('the', 'cat', 'sat', 'on', 'a', 'mat')
for i,j in enumerate(a):
    data = (i, j)
    print (data) 
word = input('Type a word out of this sentence - \'The cat sat on a mat\' : ')
word = word.lower()
print(word.find(data))

This is my code, and basically, when a user types in a word from the sentence, i want to find the index position and word from data, then print it. Please can you help me to do this very simply, as i am just a beginner. Thanks :) (Sorry if i haven't explained very well)


Solution

  • You are trying the wrong direction.

    If you have a string and call find you search for another string in that string:

    >>> 'Hello World'.find('World')
    6
    

    What you want is the other way around, find a string in a tuple. For that use the index method of the tuple:

    >>> ('a', 'b').index('a')
    0
    

    This raises a ValueError if the element is not inside the tuple. You could do something like this:

    words = ('the', 'cat', 'sat', 'on', 'a', 'mat')
    word = input('Type a word')
    try:
        print(words.index(word.lower()))
    except ValueError:
        print('Word not in words')