【问题标题】:Python - concatenate NoneType and string in a new listPython - 在新列表中连接 NoneType 和字符串
【发布时间】:2017-08-30 19:56:03
【问题描述】:

问题

如何在新列表中连接 None 和字符串?

>>> 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'>
>>>

【问题讨论】:

  • new_list = [a, b]
  • 如果使用列表连接,ab 都必须是列表:a = [None]b=['apple,banana,cherry']
  • 两个代码不同,因此结果也不同。使用预期的输出代码得到预期的结果。你能解释一下你的疑问吗?
  • @BrianRodriguez 非常感谢!现在可以了!

标签: python python-3.x


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2020-02-21
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多