[英]Inserting a string into a list without getting split into characters
我是 Python 新手,找不到將字符串插入列表而不將其拆分為單個字符的方法:
>>> list=['hello','world']
>>> list
['hello', 'world']
>>> list[:0]='foo'
>>> list
['f', 'o', 'o', 'hello', 'world']
我該怎么做才能擁有:
['foo', 'hello', 'world']
搜索了文檔和網絡,但這不是我的一天。
要添加到列表的末尾:
list.append('foo')
在開頭插入:
list.insert(0, 'foo')
堅持你用來插入它的方法,使用
list[:0] = ['foo']
http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types
另一種選擇是使用重載的+ 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']
不要使用列表作為變量名。 這是一個內置的,你正在屏蔽。
要插入,請使用列表的插入功能。
l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']
您必須添加另一個列表:
list[:0]=['foo']
ls=['hello','world']
ls.append('python')
['hello', 'world', 'python']
或(使用insert
功能,您可以在列表中使用索引位置)
ls.insert(0,'python')
print(ls)
['python', 'hello', 'world']
我建議添加“+”運算符如下:
列表 = 列表 + ['foo']
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.