Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #28343

Re: get the matched regular expression position in string.

References <CA+YdQ_4xRsyPaXgEpc6UEA9NUWoQp3GZGijQYncBStZg5ExYFw@mail.gmail.com>
Date 2012-09-03 01:36 -0700
Subject Re: get the matched regular expression position in string.
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.133.1346661375.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Sep 3, 2012 at 1:18 AM, contro opinion <contropinion@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: get the matched regular expression position in string. Chris Rebert <clp2@rebertia.com> - 2012-09-03 01:36 -0700

csiph-web