Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list to a string [duplicate]

Tags:

python

I have extracted some data from a file and want to write it to a second file. But my program is returning the error:

sequence item 1: expected string, list found 

This appears to be happening because write() wants a string but it is receiving a list.

So, with respect to this code, how can I convert the list buffer to a string so that I can save the contents of buffer to file2?

file = open('file1.txt','r') file2 = open('file2.txt','w') buffer = [] rec = file.readlines() for line in rec :     field = line.split()     term1 = field[0]     buffer.append(term1)     term2 = field[1]     buffer.append[term2]     file2.write(buffer)  # <== error file.close() file2.close() 
like image 424
PARIJAT Avatar asked May 25 '10 15:05

PARIJAT


People also ask

How do I turn a list into a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Does converting a set to list remove duplicates?

When you convert a list into a set, all the duplicates will be removed. The set can then be converted back into a list with list() . The drawback of this method is that the use of set() also changes the original list order, which is not restored after it is converted back into a list.

How do I convert a list to a string in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

How do I make a list of strings in one string in Python?

Use the join() Method to Convert the List Into a Single String in Python. The join() method returns a string in which the string separator joins the sequence of elements. It takes iterable data as an argument. We call the join() method from the separator and pass a list of strings as a parameter.


2 Answers

Try str.join:

file2.write(' '.join(buffer)) 

Documentation says:

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

like image 198
miku Avatar answered Oct 10 '22 09:10

miku


''.join(buffer) 
like image 20
blokeley Avatar answered Oct 10 '22 08:10

blokeley