我如何从另一个变量中的用户输入中找到一个词?

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

这是我的代码:

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

这是我的代码,基本上,当用户输入句子中的单词时,我想从 data 中找到索引位置和单词,然后打印出来。 请你能帮我很简单地做到这一点,因为我只是一个初学者。谢谢:)(对不起,如果我解释得不是很好)

只需使用 a.index(word) 而不是 word.find(data)。您只需要在 a 中找到 word,您不需要 for 循环,因为它所做的只是不断重新分配 data.

您的最终结果将如下所示:

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

因为你想要a出现word的索引,你需要把word.find(data)改成a.index(word))

如果单词不在 a 中,这将抛出一个 ValueError,您可以捕捉到:

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

首先,您不需要循环,因为它所做的只是将元组的最后一个元素分配给数据。

所以,你需要做这样的事情:

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

你试错方向了。

如果您有一个字符串并调用 find,您将在该字符串中搜索另一个字符串:

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

你想要的是反过来,在元组中找到一个字符串。为了那个用途 元组的 index 方法:

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

如果元素不在元组内,则会引发 ValueError。你可以这样做:

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