search re and put in a list??

Alex Martelli aleax at aleax.it
Mon Sep 16 21:01:17 CEST 2002


jubafre at brturbo.com wrote:

> i have 3 lists:
> 
> mem=['7','8', '9']
> labels['D1','D2','D3']
> S=['20 D1', '30 D2', '10 D3', 'F0', '  3', '  2', '  0']
> 
> I want to put mem in s trougth of labels.
> 
> #+++++++++++++++++++++++++++++++++++++++++++++
> final=[]
> for i in range(len(j)):
>     for c in range(len(s)):
>         p= re.compile(labels[i])
>         t1=p.search(s[c])
>         if t1:
>             t=sub(p, j[i], s[c].strip())
>             final.append(t)
> print final
> #+++++++++++++++++++++++++++++++++++++++++++++
> 
> but doing like this i have just de nodes replaced,
> ['20 7', '30 8', '10 9']
> 
> and i want the replaced and the not replaced in order like this:
> ['20 7', '30 8', '10 9', 'F0', '  3', '  2', '  0']

So you want to replace each occurrence of labels[x] with
mem[x] in each string in the list of strings S, to
produce the list of strings final.  That seems to be
just what the sub method of RE objects is for, e.g.:

final = S[:]
for label, smem in zip(labels, mem):
    labelre = re.compile(label)
    for i in range(len(final)):
        final[i] = labelre.sub(final[i], smem)

If the labels and mem lists are long, you could find
the following alternative faster -- try both:

repdict = dict(zip(labels, mem))
big_re = re.compile('|'.join(labels))
def replacer(mo, repdict=repdict):
    return repdict[mo.group()]
final = [ big_re.sub(x, replacer) for x in S ]


Alex




More information about the Python-list mailing list