get the matched regular expression position in string.

Vlastimil Brom vlastimil.brom at gmail.com
Mon Sep 3 07:36:01 EDT 2012


2012/9/3 contro opinion <contropinion at gmail.com>:
> 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.
> how can I get it in python ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hi,
you can use re.finditer to match all "," and the start() method of the
respective matches;
cf.:
http://docs.python.org/library/re.html#match-objects


>>> import re
>>> [m.start() for m in re.finditer(r",", "ha,hihi,aaaaa,ok")]
[2, 7, 13]
>>>

[The obtained indices are zero-based, as has already been mentioned.]

hth,
  vbr



More information about the Python-list mailing list