2

I'm trying to insert a String into a list.

I got this error:

TypeError: can only concatenate 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!

1
  • 2
    You talk about inserting in a list, but you have file_content[:10] and rss_xml[11:]. First those are two different lists (and here I'm assuming that rss_xml is a list), and second you will miss out the 10th element doing that. Commented Jan 14, 2010 at 17:50

4 Answers 4

9

try

file_content[:10] + [var1] + rss_xml[11:] 
Sign up to request clarification or add additional context in comments.

Comments

3

Lists have an insert method, so you could just use that:

file_content.insert(10, var1) 

Comments

2

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'] 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.