String + number split

Stevie_mac no.email at please.com
Mon Apr 12 15:07:43 EDT 2004


> It's impossible to say if it's more elegant, since you didn't
> post your attempt.
    Yeh, sorry bout tha!

>  (Homework?  I'll assume not.)
    Only a student of life!

Heres my solution...

import string
def makefont(sFontName):
    num = []
    nam = []
    acnt = 0
    #reverse it
    l = list(sFontName); l.reverse(); ''.join(l)
    sFontName = string.join(l,'')
     #now loop it while isdigit(), store number, then store alphas
    for c in sFontName:
        if c.isdigit() and acnt == 0:
            num.append(c)
        elif c.isalpha() or acnt > 1:
            acnt += 1
            nam.append(c)
    nam.reverse()
    num.reverse()
    return (string.join( nam, '' ), int(string.join( num, '' )))

Now you see why i was asking for a more elegant solution!

PS, the number on the end may vary  &  the _ could be any non alpha char!

 font12        becomes         ('font',12)
 arial_14      becomes        ('arial',14)
 arial__8      becomes        ('arial',8)
 times 6      becomes        ('times',6)



"Peter Hansen" <peter at engcorp.com> wrote in message news:mfydnfKTtqtWRufdRVn-uQ at powergate.ca...
> 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)
>
  (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')
>
> I wouldn't actually code it this way myself, but it meets
> your requirements as stated.
>
> -Peter






More information about the Python-list mailing list