2010-01-14 42 views
2

我想插入一個字符串到列表中。因爲我想這如何連接python中的列表?

TypeError: can only concatenate list (not "tuple") to list 

我得到這個錯誤

var1 = 'ThisIsAString' # My string I want to insert in the following list 
file_content = open('myfile.txt').readlines() 
new_line_insert = file_content[:10] + list(var1) + rss_xml[11:] 
open('myfile.txt', 'w').writelines(new_line_insert) 

的myfile.txt的內容保存在 「FILE_CONTENT」 爲列表。 我要插入的10日線後的字符串VAR1,這就是爲什麼我做

file_content[:10] + list(var1) + rss_xml[11:] 

但名單(VAR1)不起作用。我怎樣才能使這個代碼工作? 謝謝!

+2

請您談一下在列表中插入,但你必須FILE_CONTENT [:10 ]和rss_xml [11:]。首先,這些是兩個不同的列表(在這裏我假設rss_xml *是一個列表),其次,你會錯過第10個元素。 – 2010-01-14 17:50:27

回答

9

嘗試

file_content[:10] + [var1] + rss_xml[11:] 
3

列表有一個插入方法,所以你可以只使用:

file_content.insert(10, var1) 
1
file_content = file_content[:10] 
file_content.append(var1) 
file_content.extend(rss_xml[11:]) 
2

重要的是要注意 「名單(VAR1)」 正試圖轉換var1列表。由於VAR1是一個字符串,它會是這樣的:

 
>>> list('this') 
['t', 'h', 'i', 's'] 

或者,換句話說,將字符串轉換爲字符的列表。這是創建一個列表,其中VAR1是一個元素,它是最容易通過將「[]」周圍的元素來實現不同的:

 
>>> ['this'] 
['this']