splitting a string into 2 new strings
P at draigBrady.com
P at draigBrady.com
Wed Jul 2 09:37:17 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.
import re
molecule_re = re.compile("(.+?)([0-9]+)")
def processMolecule(molecule):
elements=[]
numbers=[]
for item in molecule.split():
element, number = molecule_re.findall(item)[0]
elements.append(element)
numbers.append(number)
elements = ' '.join(elements)
numbers = ' '.join(numbers)
return (elements, numbers)
print processMolecule('C6 H12 O6')
More information about the Python-list
mailing list