String + number split

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Apr 12 19:12:15 EDT 2004


"Stevie_mac" <no.email at please.com> wrote in message
news:c5epc8$1scu$1 at news.wplus.net...
> > 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)
>

(You might find using pyparsing a little more readable than regexp...)

-------------------------------------------
# download pyparsing at http://pyparsing.sourceforge.net
from pyparsing import Word, alphas, CharsNotIn, nums, Optional

str2int = lambda s,l,t: [int(t[0])]
fontNameSpec = ( Word(alphas).setResultsName("font") +
                 Optional( CharsNotIn(alphas+nums).suppress() ) +
                 Word(nums).setParseAction(str2int).setResultsName("size") )

testdata = [ "font12", "arial_14", "arial__8", "times 6" ]

for fname in testdata:
    results = fontNameSpec.parseString( fname )
    print results
    for k in results.keys():
        print "-", "results."+k, ":", results[k]
    print

-------------------------------------------

prints:
['font', 12]
- results.font : font
- results.size : 12

['arial', 14]
- results.font : arial
- results.size : 14

['arial', 8]
- results.font : arial
- results.size : 8

['times', 6]
- results.font : times
- results.size : 6





More information about the Python-list mailing list