How do i find the position of MORE THAN ONE substr

2020-04-21 05:40发布

问题:

The following code displays the position of "word" if it appears once in the string. How can i change my code so that if the "word" appears more than once in the string, it will print all positions?

string = input("Please input a sentence: ")
word = input("Please input a word: ")
string.lower()
word.lower()
list1 = string.split(' ')
position = list1.index(word)
location = (position+1)
print("You're word, {0}, is in position {1}".format (word, location))

回答1:

sentence = input("Please input a sentence: ")
word = input("Please input a word: ")
sentence = sentence.lower()
word = word.lower()
wordlist = sentence.split(' ')
print ("Your word '%s' is in these positions:" % word)
for position,w in enumerate(wordlist):
    if w == word:
        print("%d" % position + 1)


回答2:

Use enumerate:

[i for i, w in enumerate(s.split()) if w == 'test']

Example:

s = 'test test something something test'

Output:

[0, 1, 4]

But i guess it's not what you are looking for, if you need starting indexes for words in a string i would recommend to use re.finditer:

import re

[w.start() for w in re.finditer('test', s)]

And the output for the same s would be:

[0, 5, 30]


回答3:

Another solution that does not split on space.

def multipos(string, pattern):

    res = []
    count = 0
    while True:
        pos = string.find(pattern)
        if pos == -1:
            break
        else:
            res += [pos+count]
            count += pos+1
            string = string[pos+1:]

    return res


test = "aaaa 123 bbbb 123 cccc 123"
res = multipos("aaaa 123 bbbb 123 cccc 123", "123")
print res
for a in res:
    print test[a:a+3]

And the script output :

% python multipos.py
[5, 14, 23]
123
123
123