我正在編寫一個程序,用戶必須輸入一組字符串。然後他們選擇一個可能或不可能在字符串中的關鍵字。如果是,那麼程序將遍歷字符串並查看關鍵字出現的次數,並將其打印到屏幕上。我已經這樣做了,但是如果關鍵字出現兩次。我如何得到它,如果這個詞出現兩次,那麼程序將打印它的所有位置?如何返回字符串中出現兩次的單詞的位置?
這是我到目前爲止有:
#Start by making a string
String = input("Please enter a set of string characters.\n")
#Make the user choose a keyword
Keyword = input("Please enter a keyword that we can tell you the position of.\n")
#Split the string into single words assigning the position to the word after the space
IndivualWords = String.split(' ')
#Start an IF statement
if Keyword in IndivualWords:
#If the IF is true then access the index and assign the keyword a position
pos = IndivualWords.index(Keyword)
#Print the position of the word
print (pos +1)
else:
#Print an error
print("That word is not in the string.")
[字符串中的子串的基本索引復發(蟒蛇)](可能的重複http://stackoverflow.com/questions/ 6987702/basic-indexing-recurrings-of-a-substring-within-a-string-python) – FamousJameous
http://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an - 元素在列表中? –
這可能有所幫助:https://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python @Chris_Rands這個問題並不是真的類似於這個雖然 – Dartmouth