Find start and end positions of all occurrences within a string in Python

旧时模样 提交于 2019-12-23 02:20:23

问题


If you have a sequence:

example='abcdefabcdefabcdefg'

and your searching for:

searching_for='abc'

what function would give you a list with all the positions?

positions=[(0,2),(6-8),(12-14)]

i created a window list that splits 'example' by 3 so it goes from 'abc','bcd','cde'

windows=['abc', 'bcd', 'cde', 'def', 'efa', 'fab', 'abc', 'bcd', 'cde', 'def', 'efa', 'fab', 'abc', 'bcd', 'cde', 'def']

and used a for loop

for i in windows:
    if i == 'abc':

thats where i get stuck . . .


回答1:


You can use regular expressions; the match objects come with position information attached. Example using Python 2:

>>> import re
>>> example = 'abcdefabcdefabcdefg'
>>> for match in re.finditer('abc', example):
        print match.start(), match.end()
0 3
6 9 
12 15



回答2:


The re module provides what you need.

import re
print [(m.start(0), m.end(0)) for m in re.finditer('abc', 'abcdefabcdefabcdefg')]



回答3:


This is elegantly expressed by a list comprehension:

positions = [(i, i + len(searching_for) - 1)
             for i in xrange(len(example))
             if example[i:].startswith(searching_for)]

Note that it's often more useful to have the end index point after the last character, rather than to the last character as you asked for (and the above code provides).



来源:https://stackoverflow.com/questions/8459412/find-start-and-end-positions-of-all-occurrences-within-a-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!