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

Paul Rubin http
Thu Oct 12 14:59:19 EDT 2006


"RickMuller" <rpmuller at gmail.com> writes:
> 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

Untested, but maybe more in current Pythonic style:

 def parseline(line,format):
     xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
     result = []
     words = line.split()
     for f,w in zip(format, words):
        trans = xlat[f]
        if trans is not None:
           result.append(trans(w))
     return result

Differences:
  - doesn't ignore improper format characters, raises exception instead
  - always returns values in a list, including as an empty list if
    there's no values
  - uses iterator protocol and zip to avoid ugly index variable
    and subscripts



More information about the Python-list mailing list