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"