2016-04-30 31 views
0

这是我的代码:如何从另一个变量中的用户输入中找到一个单词?

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索引位置和字,然后打印。 请你能帮我做到这一点很简单,因为我只是一个初学者。谢谢:)(对不起,如果我没有解释得很好)

回答

2

您正在尝试错误的方向。

如果你有一个字符串,并调用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') 
+0

谢谢你,我真的很明白这一点 –

2

只需使用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)) 
2

既然你想要的a的索引,其中,word发生时,您需要更改word.find(data)a.index(word))

,这将抛出一个ValueError如果字是不是在a,你能赶上:

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

所以我不需要枚举和数据位? –

+0

@ClareJordan根本不是 – timgeb

1

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

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

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') 
相关问题