Pythonic way to concatenate string to None

Viewed 359

I'm using ElementTree to iterate through XML elements, and I'm appending line breaks to the every element's tail. ElementTree returns None if the element has no tail. This means that whenever there is no tail, an error is thrown whenever I try to concatenate another string to it, since you can't concatenate None and a str.

>>> a = None
>>> b = "string"
>>> a += b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

What would the most compact way to account for possibility of None when concatenating a string? I'm currently using the code below, but I suspect there is a simpler, more Pythonic way to rewrite it.

if element.tail:
    element.tail += "\n"
else:
    element.tail = "\n"
2 Answers

A short way to take care of None when concatenating a string is using a str conversion with or:

a = None
b = "string"
str(a or "") + "\n"  # --> '\n'
str(b or "") + "\n"  # --> 'string\n'

PEP-8 discourages string additions unless straightforward especially in a loop because string addition may be costly as strings are immutable.

What is recommended instead and is slightly more pythonic is to append the strings to a list and use join on it.

Combining that with @Franco Morero 's solution for adding None type.

x = []
for element in XMLTree:
    x.append((element.tail or ""))
finalstring = "\n".join(x)
Related