Converting a list to a string

Python

Python Problem Overview


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()

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

''.join(buffer)

Solution 3 - Python

file2.write( str(buffer) )

Explanation: str(anything) will convert any python object into its string representation. Similar to the output you get if you do print(anything), but as a string.

NOTE: This probably isn't what OP wants, as it has no control on how the elements of buffer are concatenated -- it will put , between each one -- but it may be useful to someone else.

Solution 4 - Python

buffer=['a','b','c']
obj=str(buffer)
obj[1:len(obj)-1]

will give "'a','b','c'" as output

Solution 5 - Python

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

Solution 6 - Python

Method 1:

import functools
file2.write(functools.reduce((lambda x,y:x+y), buffer))

Method 2:

import functools, operator
file2.write(functools.reduce(operator.add, buffer))

Method 3:

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

Solution 7 - Python

# it handy if it used for output list
list = [1, 2, 3]
stringRepr = str(list)
# print(stringRepr)
# '[1, 2, 3]'

Solution 8 - Python

From the official Python Programming FAQ for Python 3.6.4:

>What is the most efficient way to concatenate many strings together? str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

>To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

chunks = []
for s in my_strings:
    chunks.append(s)
result = ''.join(chunks)

>(another reasonably efficient idiom is to use io.StringIO)

>To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

result = bytearray()
for b in my_bytes_objects:
    result += b

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPARIJATView Question on Stackoverflow
Solution 1 - PythonmikuView Answer on Stackoverflow
Solution 2 - PythonblokeleyView Answer on Stackoverflow
Solution 3 - PythonToolmakerSteveView Answer on Stackoverflow
Solution 4 - PythonSaurabhView Answer on Stackoverflow
Solution 5 - PythonTendayi MawusheView Answer on Stackoverflow
Solution 6 - PythonShandeep MurugasamyView Answer on Stackoverflow
Solution 7 - PythonLurking ElkView Answer on Stackoverflow
Solution 8 - PythonchbView Answer on Stackoverflow