的Python序列提供index
方法。它给你一个元素的索引,或者如果元素不在序列中,则会产生一个错误。在字符串上,它允许您查找子字符串。
>>> 'hello world'.index('world')
6
>>> 'hello world'.index('word')
ValueError: substring not found
基本上,你必须添加输入的句子和单词来搜索。而已。
print("Insert sentence without punctuation...")
sentence=input() # get input, store it to name `sentence`
print("Insert word to find...")
word=input()
try:
idx = sentence.index(word)
except ValueError: # so it wasn't in the sentence after all...
print('Word', word, 'not in sentence', repr(sentence))
else: # if we get here, IndexError was NOT thrown
print('Word', word, 'first occurs at position', idx)
这里有一些注意事项,例如'fooworldbar'也会匹配。这些事情的正确处理取决于人们想要的东西。我猜你实际上想要单词职位。
如果您需要在“的n
个字”的含义位置,你必须改变句子单词的列表。 str.split
这样做。然后您可以再次使用index
。另外,如果您想全部职位,您必须反复调用索引。
print("Insert sentence without punctuation...")
sentence = input() # get input, store it to name `sentence`
words = sentence.split() # split at whitespace, creating a list of words
print("Insert word to find...")
word=input()
positions, idx = [], -1
while idx < len(words):
try:
idx = words.index(word, idx+1)
except ValueError: # so it wasn't in the rest of the sentence after all...
break
else: # if we get here, IndexError was NOT thrown
positions.append(idx) # store the index to list of positions
# if we are here, we have searched through the whole string
if positions: # positions is not an empty list, so we have found some
print('Word', word, 'appears at positions', ', '.join(str(pos) for pos in positions))
else:
print('Word', word, 'is not in the sentence')
你预计' '字' =='COUNTRY''是真的吗?你的意思是说,如果word =='COUNTRY''? – doctorlove
这听起来像是一个很短的时间的重大任务.. –
这段代码是完全没用的。你有没有运行过这段代码?你能告诉我们这段代码的哪部分不起作用吗? – pt12lol