splitting a string into 2 new strings

trp trp at smyrncable.net
Wed Jul 2 08:20:20 EDT 2003


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