How to find all occurrences of a substring

0 votes

Python has string.find() and string.rfind() to get the index of a substring in a string.

I'm wondering whether there is something like string.find_all() which can return all found indexes (not only the first from the beginning or the first from the end).

For example:

string = "test test test test"

print string.find('test') # 0
print string.rfind('test') # 15

#this is the goal
print string.find_all('test') # [0,5,10,15]
Nov 24, 2020 in Python by Rajiv
• 8,880 points

1 answer to this question.

0 votes

There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:

import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]

If you want to find overlapping matches, lookahead will do that:

[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]

If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:

search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]

re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you're only iterating through the results once.

answered Nov 24, 2020 by Gitika
• 65,850 points

Related Questions In Python

0 votes
1 answer

How to replace all occurrences of a string?

The general pattern is str.split(search).join(replacement) This used to be ...READ MORE

answered Nov 26, 2020 in Python by Gitika
• 65,850 points
0 votes
1 answer

how to find factorial of a number?

You can find factorial by many ways. ...READ MORE

answered May 4, 2018 in Python by aayushi
• 750 points
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29, 2019 in Python by rajesh
• 1,230 points
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,719 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
1 answer
0 votes
1 answer

How to match all occurrences of a regex?

Using scan should do the trick: string.scan(/regex/) READ MORE

answered Nov 24, 2020 in Python by Gitika
• 65,850 points