splitting a string into 2 new strings

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Jul 2 16:24:25 CEST 2003

>>>>> "Mark" == Mark Light <light at soton.ac.uk> writes:

    Mark> Hi, I have a string e.g. 'C6 H12 O6' that I wish to split up
    Mark> to give 2 strings 'C H O' and '6 12 6'.  I have played with
    Mark> string.split() and the re module - but can't quite get
    Mark> there.

    Mark> Any help would be greatly appreciated.

Here's an example using re:

  import re

  def pairs(l):
      return [[l[i], l[i+1]] for i in range(0, len(l), 2)]

  splits = [ t for t in re.split('([A-Z])(\d+) *', 'C6 H12 O6') if len(t)>0]

  for letter, number in pairs(splits):
      print letter, number

pairs is a function to loop over a list in pairs.

John Hunter

More information about the Python-list mailing list