alternating string replace

Paul McGuire ptmcg at austin.rr.com
Wed Jan 9 21:34:14 CET 2008


On Jan 9, 7:41 am, "Neil Cerutti" <mr.ceru... at gmail.com> wrote:
> On Jan 9, 2008 5:34 AM, cesco <fd.calabr... at gmail.com> wrote:
>
> > Hi,
>
> > say I have a string like the following:
> > s1 = 'hi_cat_bye_dog'
> > and I want to replace the even '_' with ':' and the odd '_' with ','
> > so that I get a new string like the following:
> > s2 = 'hi:cat,bye:dog'
> > Is there a common recipe to accomplish that? I can't come up with any
> > solution...
>
> > Thanks in advance
>
> Hum, hum... If I had a hammer...
>
> frompyparsingimport *
>
> word = Word(alphas)
> sep = Literal('_').suppress()
> pair = Group(word + sep + word)
> pairs = delimitedList(pair, '_')
>
> print ','.join(':'.join(t) for t in
>                pairs.parseString('hi_cat_bye_dog').asList())
>
> --
> Neil Cerutti <mr.cerutti+pyt... at gmail.com>

My suspicious nature sees the following coming along...

d1 = eval("{"+s2+"}")

You can have pyparsing create the tuples for you, and then convert to
a dict at the end with a constructor - no eval needed.

from pyparsing import *

word = Word(alphas)
sep = Literal('_').suppress()
pair = Group(word + sep + word).setParseAction(lambda toks:
tuple(*toks))
pairs = delimitedList(pair, '_')

print dict(pairs.parseString('hi_cat_bye_dog').asList())

Prints:

{'bye': 'dog', 'hi': 'cat'}

-- Paul



More information about the Python-list mailing list