开发者

Change array that might contain None to an array that contains "" in python

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开发者_如何学Go string or Unicode, NoneType found

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


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.


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, ''…).


You can also use the built-in filter function:

>>> l = ["Hello", None, "green"]
>>> filter(None, l)
['Hello', 'green']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜