简体   繁体   中英

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)

Just use a.index(word) instead of word.find(data) . You just need to find word in a , and you don't need your for loop because all it does is keep reassigning data .

Your final result would look something like this:

a = ('the', 'cat', 'sat', 'on', 'a', 'mat')
word = input('Type a word out of this sentence - \'The cat sat on a mat\' : ').lower()
print(a.index(word))

Since you want the index of a where word occurs, you need to change word.find(data) to a.index(word)) .

This will throw a ValueError if the word is not in a , which you could catch:

try:
    print(a.index(word))
except ValueError:
    print('word not found')

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

First, you don't need your loop because all it does is just assign the last element of your tuple to data.

So, you need to do something like this:

a = ('the', 'cat', 'sat', 'on', 'a', 'mat') # You can call it data
word = input('Type a word out of this sentence - \'The cat sat on a mat\' : ')
word = word.lower()
try:
    print(a.index(data))
except ValueError:
    print('word not found')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM