将字符串添加到列表 [英] Adding a string to a list
本文介绍了将字符串添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> b = []
>>> c = '1234'
>>> b += c
>>> b
['1', '2', '3', '4']
>>>
这是怎么回事?这不行吧?还是我缺少明显的东西?
What is happening here ? This should not work, right ? or am I missing something obvious?
>>> b = []
>>> c = '1234'
>>> b + c
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
b + c
TypeError: can only concatenate list (not "str") to list
>>>
然后a += b
并不总是等同于a = a + b
吗?
Then a += b
is not always equivalent to a = a + b
?
推荐答案
字符串是可迭代的:元素是字符串的字符.在将可迭代项添加到列表时,可迭代项的 elements 会附加到列表中.
Strings are iterable: the elements are the string's characters. When you add an iterable to a list, the iterable's elements get appended to the list.
以下任何一项都可以满足您的期望(即追加字符串,而不用字符串的字符扩展列表):
Either of the following will do what you're expecting (i.e. append the string, not extend the list with the string's characters):
b += [c]
或
b.append(c)
这篇关于将字符串添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文