简体   繁体   English

将字符串插入列表而不拆分为字符

[英]Inserting a string into a list without getting split into characters

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.搜索了文档和网络,但这不是我的一天。

To add to the end of the list:要添加到列表的末尾:

list.append('foo')

To insert at the beginning:在开头插入:

list.insert(0, 'foo')

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

Another option is using the overloaded + operator :另一种选择是使用重载的+ operator

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

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

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

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

您必须添加另一个列表:

list[:0]=['foo']
ls=['hello','world']
ls.append('python')
['hello', 'world', 'python']

or (use insert function where you can use index position in list)或(使用insert功能,您可以在列表中使用索引位置)

ls.insert(0,'python')
print(ls)
['python', 'hello', 'world']

I suggest to add the '+' operator as follows:我建议添加“+”运算符如下:

list = list + ['foo']列表 = 列表 + ['foo']

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM