do this with list comp?
Michael T. Babcock
mbabcock at fibrespeed.net
Fri Dec 12 12:05:14 EST 2003
python-list-request at python.org wrote:
>
> Subject:
> do this with list comp?
> From:
> John Hunter <jdhunter at ace.bsd.uchicago.edu>
> Date:
> Fri, 12 Dec 2003 10:46:58 -0600
> To:
> 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.....
>
>
def replace_blank_with_null(data):
if not data:
return "NULL"
return data
new_list = [ replace_blank_with_null(line) for line in old_list ]
Or something more like:
line_items = [ replace_blank_with_null(item) for item in line.split(",") ]
--
Michael T. Babcock
C.T.O., FibreSpeed Ltd.
http://www.fibrespeed.net/~mbabcock
More information about the Python-list
mailing list