将字符串插入到列表中,而不需要将其拆分为字符。

时间:2022-01-12 02:21:08

I'm new to Python and can't find a way to insert a string into a list without it getting split into individual characters:

我是Python的新手,我找不到一种方法可以将字符串插入到列表中,而不需要将其拆分为单个字符:

>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']

What should I do to have:

我该怎么做才能拥有:

['foo', 'hello', 'world']

Searched the docs and the Web, but it has not been my day.

搜索文档和网络,但这不是我的天。

7 个解决方案

#1


112  

To add to the end of the list:

在清单的最后增加:

list.append('foo')

To insert at the beginning:

插入开头:

list.insert(0, 'foo')

#2


16  

Sticking to the method you are using to insert it, use

坚持使用您正在使用的方法插入它,使用。

list[:0] = ['foo']

http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types

http://docs.python.org/release/2.6.6/library/stdtypes.html mutable-sequence-types

#3


10  

Another option is using the overloaded + operator:

另一种选择是使用重载+运算符:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

#4


5  

>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']

#5


4  

Don't use list as a variable name. It's a built in that you are masking.

不要使用列表作为变量名。这是一个内在的,你在掩蔽。

To insert, use the insert function of lists.

要插入,请使用列表的插入函数。

l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']

#6


3  

best put brackets around foo, and use +=

最好在foo周围加上括号,并使用+=

list+=['foo']

#7


2  

You have to add another list:

你必须添加另一个列表:

list[:0]=['foo']

#1


112  

To add to the end of the list:

在清单的最后增加:

list.append('foo')

To insert at the beginning:

插入开头:

list.insert(0, 'foo')

#2


16  

Sticking to the method you are using to insert it, use

坚持使用您正在使用的方法插入它,使用。

list[:0] = ['foo']

http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types

http://docs.python.org/release/2.6.6/library/stdtypes.html mutable-sequence-types

#3


10  

Another option is using the overloaded + operator:

另一种选择是使用重载+运算符:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

#4


5  

>>> li = ['aaa', 'bbb']
>>> li.insert(0, 'wow!')
>>> li
['wow!', 'aaa', 'bbb']

#5


4  

Don't use list as a variable name. It's a built in that you are masking.

不要使用列表作为变量名。这是一个内在的,你在掩蔽。

To insert, use the insert function of lists.

要插入,请使用列表的插入函数。

l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']

#6


3  

best put brackets around foo, and use +=

最好在foo周围加上括号,并使用+=

list+=['foo']

#7


2  

You have to add another list:

你必须添加另一个列表:

list[:0]=['foo']