Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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 ""?

like image 547
vy32 Avatar asked Dec 17 '22 00:12

vy32


2 Answers

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.

like image 112
Mark Byers Avatar answered May 10 '23 23:05

Mark Byers


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

like image 28
tzot Avatar answered May 10 '23 23:05

tzot