的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