Python 如何从另一个变量中的用户输入中查找单词?
这是我的代码:Python 如何从另一个变量中的用户输入中查找单词?,python,enumerate,Python,Enumerate,这是我的代码: 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)) 这是我的代码,基本上,当用户
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))
这是我的代码,基本上,当用户输入句子中的单词时,我想从数据中找到索引位置和单词,然后打印它。
请你帮我做这个很简单,因为我只是一个初学者。谢谢:)(如果我解释得不好,很抱歉)只需使用a.index(word)
而不是word.find(data)
。您只需要在a
中查找word
,而不需要for循环,因为它所做的只是不断重新分配数据
您的最终结果如下所示:
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 = ('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')
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')
由于您希望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')
word = input('Type a word out of this sentence - \'The cat sat on a mat\' : ').lower()
print(a.index(word))
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')
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')
你尝试了错误的方向
如果您有一个字符串并调用find
,则在该字符串中搜索另一个字符串:
>>> 'Hello World'.find('World')
6
你想要的是另一种方式,在元组中找到一个字符串。为此目的
元组的索引方法:
>>> ('a', 'b').index('a')
0
如果元素不在元组内,则会引发ValueError
。你可以这样做:
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 = ('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')
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')
所以我不需要枚举和数据位?@ClareJordan一点也不需要