do this with list comp?

J

John Hunter

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
 
D

Diez B. Roggisch

John said:
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
 
D

Dang Griffith

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,478
Latest member
ReginaldVi

Latest Threads

Top