do this with list comp?
Peter Abel
PeterAbel at gmx.net
Sat Dec 13 06:31:26 EST 2003
"Dave Brueck" <dave at pythonapocrypha.com> wrote in message news:<mailman.106.1071248302.9307.python-list at python.org>...
> > I want to replace all empty fields in a CSV line with 'NULL'.
> >
> > Here is a brute force way
> >
> > def fixline(line):
> > ret = []
> > for s in line.split(','):
> > if not len(s): ret.append('NULL')
> > else: ret.append(s)
> > return ret
> >
> > line = 'John,Bill,,,Fred'
> > print fixline(line)
> > # ['John', 'Bill', 'NULL', 'NULL', 'Fred']
> >
> > I am wondering if there is a way to do it with list comprehensions. I
> > know how I would do it with a ternary operator.....
>
> Prepare to be flooded with answers. ;-)
>
> >>> line = 'John,Bill,,,Fred'
> >>> [x or 'NULL' for x in line.split(',')]
> ['John', 'Bill', 'NULL', 'NULL', 'Fred']
>
> -Dave
>
> P.S. I guess you are sure that the fields themselves don't have commas and that
> you don't therefore need a "real" CSV parser?
And there was still a one-liner:
>>> line = 'John,Bill,,,Fred'
>>> map(lambda x:x or 'NULL',line.split(','))
['John', 'Bill', 'NULL', 'NULL', 'Fred']
Regards
Peter
More information about the Python-list
mailing list