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 ""?
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, ''…).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With