how to concatenate lists in python?
I'm trying to insert a String into a list.
I got this error:
TypeError: can only concat开发者_如何学Cenate list (not "tuple") to list
because I tried this:
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)
The content of myfile.txt is saved in "file_content" as a list. I want to insert the String var1 after the 10th line, thats why I did
file_content[:10] + list(var1) + rss_xml[11:]
but the list(var1) doesn't work. How can I make this code work? Thanks!
try
file_content[:10] + [var1] + rss_xml[11:]
Lists have an insert method, so you could just use that:
file_content.insert(10, var1)
It's important to note the "list(var1)" is trying to convert var1 to a list. Since var1 is a string, it will be something like:
>>> list('this') ['t', 'h', 'i', 's']
Or, in other words, it converts the string to a list of characters. This is different from creating a list where var1 is an element, which is most easily accomplished by putting the "[]" around the element:
>>> ['this'] ['this']
file_content = file_content[:10]
file_content.append(var1)
file_content.extend(rss_xml[11:])
精彩评论