'NoneType' 对象在 Python 列表理解中没有属性 'replace'
'NoneType' object has no attribute 'replace' in Python list comprehension
我有以下词典...
mydict = {'columns': ['col1', 'col2', 'col3'],
'rows': [['col1', 'col2', 'col3'],
['testing data 1', 'testing data 2lk\nIdrjy9dyj', 'testing data 3'],
['testing data 2', 'testing data 3', 'testing data 4'],
['testing data 3', 'testing data 4', 'testing data 5']]}
并且我正在使用以下列表推导式将 return "\n"
替换为此 "<br>"
。它工作正常,除非它在读取 json 文件时传递一个空字符串。然后它抛出错误 'NoneType' object has no attribute 'replace'
。我只是不知道如何在列表理解中放入 if is not none
语句。非常感谢任何帮助..
for items in mydict['rows']:
mydict['rows'][i] = [item.replace("\n","<br>") for item in items]
i += 1
您可以在这里使用布尔表达式:
[item and item.replace("\n","<br>") for item in items]
如果 item
被认为是真的,这只会调用 item.replace()
; None
和空字符串都被认为是假的。
如果您想过滤掉任何None
项,您可以在列表理解中添加测试:
[item.replace("\n","<br>") for item in items if item is not None]
删除 None
值或
[item.replace("\n","<br>") for item in items if item]
只保留非空值。
我有以下词典...
mydict = {'columns': ['col1', 'col2', 'col3'],
'rows': [['col1', 'col2', 'col3'],
['testing data 1', 'testing data 2lk\nIdrjy9dyj', 'testing data 3'],
['testing data 2', 'testing data 3', 'testing data 4'],
['testing data 3', 'testing data 4', 'testing data 5']]}
并且我正在使用以下列表推导式将 return "\n"
替换为此 "<br>"
。它工作正常,除非它在读取 json 文件时传递一个空字符串。然后它抛出错误 'NoneType' object has no attribute 'replace'
。我只是不知道如何在列表理解中放入 if is not none
语句。非常感谢任何帮助..
for items in mydict['rows']:
mydict['rows'][i] = [item.replace("\n","<br>") for item in items]
i += 1
您可以在这里使用布尔表达式:
[item and item.replace("\n","<br>") for item in items]
如果 item
被认为是真的,这只会调用 item.replace()
; None
和空字符串都被认为是假的。
如果您想过滤掉任何None
项,您可以在列表理解中添加测试:
[item.replace("\n","<br>") for item in items if item is not None]
删除 None
值或
[item.replace("\n","<br>") for item in items if item]
只保留非空值。