views:

58

answers:

3

I have a python function that gets an array called row.

Typically row contains things like:

["Hello","goodbye","green"]

And I print it with:

print "\t".join(row)

Unfortunately, sometimes it contains:

["Hello",None,"green"]

Which generates this error:

TypeError: sequence item 2: expected string or Unicode, NoneType found

Is there an easy way to replace any None elements with ""?

+9  A: 

You can use a conditional expression:

>>> l = ["Hello", None, "green"]
>>> [(x if x is not None else '') for x in l]
['Hello', '', 'green']

A slightly shorter way is:

>>> [x or '' for x in l]

But note that the second method also changes 0 and some other objects to the empty string.

Mark Byers
Pretty slick; when did python get "if" as an operator?
vy32
@vy32, python 2.5 : http://en.wikipedia.org/wiki/Ternary_operation#Python
Stephen
Since the result is just going to be consumed by `str.join`, it could make a lot of sense to use a generator expression instead of a list comprehension. Consider using round brackets instead of square brackets in line 2 of the answer.
Wesley
A: 

You can also use the built-in filter function:

>>> l = ["Hello", None, "green"]
>>> filter(None, l)
['Hello', 'green']
twneale
This may not be a good solution to this particular problem. The question mentions that the tab character `\t` is to be used as the separator. Removing an element of the list outright may lead to one fewer tab character being emitted.
Wesley
This doesn't do what I want ,because the output list has a different number of elements than the input list.
vy32
+1  A: 

You can use a generator expression in place of the array:

print "\t".join(fld or "" for fld in row)

This will substitute the empty string for everything considered as False (None, False, 0, 0.0, ''…).

ΤΖΩΤΖΙΟΥ
I didn't know that Python let you use "or" like that at this point. Neat. Thanks.
vy32