do this with list comp?
Diez B. Roggisch
deets_noospaam at web.de
Sat Dec 13 09:46:15 EST 2003
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
More information about the Python-list
mailing list