我正在使用 ElementTree 迭代 XML 元素,并将换行符附加到每个元素的 tail
中。 。 ElementTree 返回 None
如果元素没有尾部。这意味着只要没有尾部,每当我尝试将另一个字符串连接到它时就会抛出错误,因为您无法连接 None
和一个 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'
解释 None
可能性的最紧凑方式是什么?当连接字符串时?我目前正在使用下面的代码,但我怀疑有一种更简单、更 Pythonic 的方法来重写它。
if element.tail:
element.tail += "\n"
else:
element.tail = "\n"
最佳答案
连接字符串时处理 None
的一种简短方法是使用 str
与 or
转换:
a = None
b = "string"
str(a or "") + "\n" # --> '\n'
str(b or "") + "\n" # --> 'string\n'
关于将字符串连接到 None 的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67493245/