我在写一个程序,用户必须输入一组字符串。然后他们选择一个关键字,这个关键字可能在字符串中,也可能不在字符串中。如果是这样的话,程序会在字符串中运行,看看关键字出现了多少次,并将其打印到屏幕上。我已经这样做了,但如果关键字出现两次。我如何得到它,如果这个词出现两次,那么程序将打印它的所有位置?你知道吗
到目前为止,我的情况是:
#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.")
您可以使用regex方法^{}
或者如果需要子字符串的范围:
您可以使用re.finditer,下面是您的示例中的一个小示例:
使用
enumerate()
在“een”是关键字的示例中,line
输入:相关问题 更多 >
编程相关推荐