Question
Python has str.find() and str.rfind() to get the index of a substring in a string.
I'm wondering whether there is something like str.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]
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expression module re:
If you want to find overlapping matches, lookahead will do that:
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')]
- #[1]
沒有留言:
張貼留言