String + number split

Joe Mason joe at notcharles.ca
Mon Apr 12 16:47:04 EDT 2004


In article <c5epc8$1scu$1 at news.wplus.net>, Stevie_mac wrote:
> 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)

>>> import re
>>> def fsplit(fs):
...     r = re.compile("""                            
...         ([A-Za-z]+) # group 1: 1 or more letters
...         [^0-9]*     # 0 or more non-digits; not a group because not in ()
...         ([0-9]+)    # group 2: 1 or more numbers
...         """, re.VERBOSE)
...     m = r.match(fs)
...     if m: return (m.group(1), m.group(2))
...     else: raise ValueError, "Badly formatted font string"
... 
>>> fsplit('font12')
('font', '12')
>>> fsplit('arial_14')
('arial', '14')
>>> fsplit('arial_8')
('arial', '8')
>>> fsplit('times 6')
('times', '6')

Joe



More information about the Python-list mailing list