do this with list comp?

Dang Griffith noemail at noemail4u.com
Thu Dec 18 19:44:42 CET 2003


On Fri, 12 Dec 2003 10:46:58 -0600, John Hunter
<jdhunter at ace.bsd.uchicago.edu> 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.....
>
>John Hunter
I'd go with Dave Brueck's answer:
    [x or 'NULL' for x in line.split(',')]

The "trick" here is the "hidden" ternary operator.

By saying "x or 'NULL' ", you are expressing the equivalent of what
would look in C, et al, like:
   x ? x : 'NULL'

In other words, if x is not null/None/empty/nil/false, evaluate to x.
Otherwise, evaluate to 'NULL'.

    --dang




More information about the Python-list mailing list