我正在编写一个程序,用户必须输入一组字符串。然后他们选择一个可能或不可能在字符串中的关键字。如果是,那么程序将遍历字符串并查看关键字出现的次数,并将其打印到屏幕上。我已经这样做了,但是如果关键字出现两次。我如何得到它,如果这个词出现两次,那么程序将打印它的所有位置?如何返回字符串中出现两次的单词的位置?
这是我到目前为止有:
#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