Re: do this with list comp?

From: Diez B. Roggisch (deets_noospaam_at_web.de)
Date: 12/13/03


Date: Sat, 13 Dec 2003 15:46:15 +0100

John Hunter wrote:

>
> 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.....

This should work:

res = [[s, 'NULL'][not len(s)] for s in line.split(",")]

Diez



Relevant Pages

  • Re: do this with list comp?
    ... >I want to replace all empty fields in a CSV line with 'NULL'. ... >Here is a brute force way ... > def fixline: ...
    (comp.lang.python)
  • do this with list comp?
    ... I want to replace all empty fields in a CSV line with 'NULL'. ... Here is a brute force way ... John Hunter ...
    (comp.lang.python)
  • Re: do this with list comp?
    ... > I want to replace all empty fields in a CSV line with 'NULL'. ... > Here is a brute force way ... > def fixline: ...
    (comp.lang.python)
  • Re: [NEWB] Dictionary instantiation?
    ... I'm working with csv module as an exercise to parse out a spreadsheet ... def author_to_dict: #Function to add each author to the dictionary ... Please take a little time to read more material about functions and scoping rules. ... read more material, experiment (Python is great for this - read about the '-i' option of the python interpreter), and post here when you run into trouble. ...
    (comp.lang.python)
  • Re: parsing csv files class
    ... I just want to make it more pythonic I also want to add capability for makeing csv file if I give it input like: ... On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy ... #!/usr/bin/env python ... def index: ...
    (comp.lang.python)