String + number split

Jack Diederich jack at performancedrivers.com
Mon Apr 12 15:23:29 EDT 2004


On Mon, Apr 12, 2004 at 02:11:23PM -0400, Peter Hansen wrote:
> Stevie_mac wrote:
> >Hello again, I can do this, but I'm sure there is a much more elegant 
> >way...
> >
> >A string, with a number on the end, strip off the number & discard any 
> >underscores
> >
> >eg...
> >
> >font12        becomes         ('font',12)
> >arial_14      becomes        ('arial',14)
> 
> It's impossible to say if it's more elegant, since you didn't
> post your attempt.  (Homework?  I'll assume not.)
> 
> >>> import re
> >>> def fsplit(fs):
> ...   return tuple(re.split('(\d+)', fs.replace('_', ''))[:2])
> ...
> >>> fsplit('font12')
> ('font', '12')
> >>> fsplit('arial_14')
> ('arial', '14')

There are many ways you could write the regexp, this is one I find
easist to read.

def mysplit(instr):
  # one or more alpha followed by zero or more non-digits followed by one or more digits
  grouper = re.compile('([a-zA-Z]+)\D*(\d+)')
  match_ob = grouper.match(instr)
  name = match_ob.groups(1)
  num = int(match_ob.groups(2))
  return (name, num)

>>> mysplit('arial_14')
('arial', 14)

I carry arround a 'coerce' method, that looks like this
def coerce(types, inputs):
  return map(lambda f,val:f(val), types, inputs)

which changes the last few lines in mysplit into
  return coerce([str, int], match_ob.groups())

-jackdied





More information about the Python-list mailing list