将字符串插入列表而不被拆分为字符
我刚开始学习Python,找不到方法把一个字符串插入到列表里,而不让它变成一个个字符:
>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']
我应该怎么做才能得到:
['foo', 'hello', 'world']
我查了文档和网上的资料,但今天运气不太好。
相关问题:
9 个回答
16
另一种选择是使用重载的 + 运算符:
>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']
23
继续使用你现在插入的方式,可以使用
list[:0] = ['foo']
http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types
162
要在列表的末尾添加内容,可以使用以下代码:
list.append('foo')
如果想要在列表的开头插入内容,可以使用这段代码:
list.insert(0, 'foo')