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


Groups > comp.lang.python > #28343 > unrolled thread

Re: get the matched regular expression position in string.

Started byChris Rebert <clp2@rebertia.com>
First post2012-09-03 01:36 -0700
Last post2012-09-03 01:36 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#28343 — Re: get the matched regular expression position in string.

FromChris Rebert <clp2@rebertia.com>
Date2012-09-03 01:36 -0700
SubjectRe: get the matched regular expression position in string.
Message-ID<mailman.133.1346661375.27098.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web