【发布时间】:2017-01-06 22:23:42
【问题描述】:
我正在编写一个程序,用户必须输入一组字符串字符。然后他们选择一个可能在字符串中也可能不在字符串中的关键字。如果是,那么程序将遍历字符串并查看关键字出现了多少次,并将其打印到屏幕上。我已经这样做了,但是如果关键字出现两次。我如何得到它,如果这个词出现两次,那么程序将打印它的所有位置?
这是我目前所拥有的:
#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.")
【问题讨论】:
-
这可能会有所帮助:stackoverflow.com/questions/3873361/…@Chris_Rands 这个问题与此并不相似
-
您可以使用count 方法为您的列表和
foreach循环。