Python - 在新列表中连接NoneType和string

时间:2017-08-30 19:56:04

标签: python python-3.x

问题

如何在新列表中连接None和string?

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

预期输出

>>> new_list = [None, 'apple,banana,cherry']
>>> print(new_list)
[None, 'apple,banana,cherry']
>>> print(type(new_list))
<class 'list'>
>>>

1 个答案:

答案 0 :(得分:1)

将项目添加到要使用append方法的列表中:

my_list = []
a = None
b = 'apple,banana,cherry'

# adds a to the list
my_list.append(a)

# adds b to the list
my_list.append(b)