searching through a string and pulling characters

Wojtek Walczak gminick at bzt.bzt
Mon Aug 18 23:43:43 CEST 2008


On Mon, 18 Aug 2008 13:40:13 -0700 (PDT), Alexnb wrote:
> Now, I am talking 1000's of these. I need to do something like this. I will
> have a number, and what I want to do is go through this text file, just like
> the example. The trick is this, those "()'s" are what I need to match, so if
> the number is 245 I need to find the 245th () and then get the all the text
> from after it until the next (). If you have an idea about the best way to
> do this I would love your help. If you made it all the way through thanks!
> ;)

findall comes to mind:

>>> a="""(string1)
... (string2)
... (string3)
... (string4)
... (string5)
... (string6)"""
>>> import re
>>> pat = re.compile("(\(.*?\))")

and now let's say you want to get fourth element:

>>> pat.findall(a)[3]
'(string4)'

To save some memory use finditer (as long as you don't have to search
for too many of these):

>>> for i in enumerate(pat.finditer(a)):
...    if i[0] == 2:
...       print i[1].group()
...
(string3)
>>>


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/



More information about the Python-list mailing list