splitting a string into 2 new strings

Mark Light light at soton.ac.uk
Wed Jul 2 14:41:03 CEST 2003


that works great - many thanks.

"trp" <trp at smyrncable.net> wrote in message
news:vg5jjqcc8d2r1f at corp.supernews.com...
> Mark Light wrote:
>
> > Hi,
> >       I have a string e.g. 'C6 H12 O6' that I wish to split up to give 2
> > strings
> > 'C H O' and '6 12 6'.  I have played with string.split() and the re
module
> > - but can't quite get there.
> >
> > Any help would be greatly appreciated.
> >
> > Thanks,
> >
> > Mark.
>
> I'm, assuming that these are chemical compounds, so you're not limited to
> one-character symbols.
>
> Here's how I'd do it
>
> import re
>
> re_pat = re.compile('([A-Z]+)(\d+)')
> text = 'C6 H12 O6'
>
> # find each component, returns list of tuples (e.g. [('C', '6'), ...]
> component = re_pat.findall(text)
>
> #split into separate lists
> symbols, counts = zip(*component)
>
> # create the strings
> symbols = ' '.join(symbols)
> counts = ' '.join(counts)
>
> --Andy
>
>
>
>
>






More information about the Python-list mailing list