如何返回字符串中出现两次的单词的位置?

2024-04-25 21:07:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个程序,用户必须输入一组字符串。然后他们选择一个关键字,这个关键字可能在字符串中,也可能不在字符串中。如果是这样的话,程序会在字符串中运行,看看关键字出现了多少次,并将其打印到屏幕上。我已经这样做了,但如果关键字出现两次。我如何得到它,如果这个词出现两次,那么程序将打印它的所有位置?你知道吗

到目前为止,我的情况是:

#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.")

Tags: ofthe字符串程序inputstringposition关键字
3条回答

您可以使用regex方法^{}

>>> keyword = 'fox'
>>> s = 'The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'

>>> from re import finditer
>>> print [match.start(0) for match in finditer(keyword, s)]
[16, 61]

或者如果需要子字符串的范围:

>>> print [(match.start(0), match.end(0)) for match in re.finditer(keyword, s)]
[(16, 19), (61, 64)]

您可以使用re.finditer,下面是您的示例中的一个小示例:

import re

sentence = input("Enter a set of string characters:")
keyword = input("Enter a keyword that we can tell you the position of:")

for m in re.finditer(keyword, sentence):
    print('{0} found {1}-{2}'.format(keyword, m.start(), m.end()))

使用enumerate()在“een”是关键字的示例中,line输入:

keyword = "een"
line = "een aap op een fiets"
for index, word in enumerate(line.split()):
    if word == keyword:
        print(index)

相关问题 更多 >