[英]how to concatenate lists in python?
我正在嘗試將String插入列表中。
我收到了這個錯誤:
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行之后插入String var1,這就是我做的原因
file_content[:10] + list(var1) + rss_xml[11:]
但列表(var1)不起作用。 如何使此代碼有效? 謝謝!
嘗試
file_content[:10] + [var1] + rss_xml[11:]
列表有一個insert方法,所以你可以使用它:
file_content.insert(10, var1)
重要的是要注意“list(var1)”試圖將var1轉換為列表。 由於var1是一個字符串,它將類似於:
>>> list('this') ['t', 'h', 'i', 's']
或者,換句話說,它將字符串轉換為字符列表 。 這不同於創建一個列表,其中var1是一個元素,通過在元素周圍放置“[]”最容易實現:
>>> ['this'] ['this']
file_content = file_content[:10]
file_content.append(var1)
file_content.extend(rss_xml[11:])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.