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


113

我是Python的新手,如果不将其拆分成单个字符,就找不到一种将字符串插入列表的方法:

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

我应该怎么做:

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

搜索了文档和网络,但这不是我的日子。

Answers:


147

要添加到列表的末尾:

list.append('foo')

要在开头插入:

list.insert(0, 'foo')

我敢肯定,大多数人都知道这一点,但只是添加:做list2 = list1.append('foo')list2 = list1.insert(0, 'foo') 将导致list2其值为None。这两个appendinsert是变异,他们正在使用,而不是返回一个新的列表清单的方法。
MoltenMuffins


15

另一种选择是使用重载+ operator

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

1
刚刚看到,您也可以在结尾处使用它: l += ['foo']
Toni Homedes i Saun

6

最好将方括号放在foo周围,并使用+ =

list+=['foo']

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

4

不要将list用作变量名。这是您掩盖的内在因素。

要插入,请使用列表的插入功能。

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

这不是很正确。insert()需要第二个论点。
拉菲·凯特勒

@RafeKettler糟糕,append是不带place参数的那个。
Spencer Rathbun


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

或(使用insert可以在列表中使用索引位置的功能)

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.