get the matched regular expression position in string.

Chris Rebert clp2 at rebertia.com
Mon Sep 3 04:36:12 EDT 2012


On Mon, Sep 3, 2012 at 1:18 AM, contro opinion <contropinion at gmail.com> wrote:
> Subject: get the matched regular expression position in string.

As is often the case in Python, string methods suffice. Particularly
for something so simple, regexes aren't necessary.

> Here is a string :
>
> str1="ha,hihi,aaaaa,ok"
>
> I want to get the position of "," in the str1,Which can count 3,8,14.

Note that Python's indices start at 0. Your example output uses 1-based indices.

> how can I get it in python ?

def find_all(string, substr):
    start = 0
    while True:
        try:
            pos = string.index(substr, start)
        except ValueError:
            break
        else:
            yield pos
            start = pos + 1

str1 = "ha,hihi,aaaaa,ok"
print list(find_all(str1, ","))  #===> [2, 7, 13]


In the future, I recommend reading the documentation for Python's string type:
http://docs.python.org/library/stdtypes.html#string-methods

What opinion are you contrary ("contro") to anyway?

Regards,
Chris



More information about the Python-list mailing list