paseline(my favorite simple script): does something similar exist?

RickMuller rpmuller at gmail.com
Thu Oct 12 14:45:42 EDT 2006


One of my all-time favorite scripts is parseline, which is printed
below

def parseline(line,format):
    xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
    result = []
    words = line.split()
    for i in range(len(format)):
        f = format[i]
        trans = xlat.get(f,'None')
        if trans: result.append(trans(words[i]))
    if len(result) == 0: return None
    if len(result) == 1: return result[0]
    return result

This takes a line of text, splits it, and then applies simple
formatting characters to return different python types. For example,
given the line

H    0.000   0.000   0.000

I can call parseline(line,'sfff') and it will return the string 'H',
and three floats. If I wanted to omit the first, I could just call
parseline(line,'xfff'). If I only wanted the first 0.000, I could call
parseline(line,'xf'). Clearly I don't do all of my parsing this way,
but I find parseline useful in a surprising number of applications.

I'm posting this here because (1) I'm feeling smug at what a bright
little coder I am, and (2) (in a more realistic and humble frame of
mind) I realize that many many people have probably found solutions to
similar needs, and I'd imaging that many are better than the above. I
would love to hear how other people do similar things.

Rick




More information about the Python-list mailing list