关于python:将列表转换为字符串

Converting a list to a string

本问题已经有最佳答案,请猛点这里访问。

我已经从一个文件中提取了一些数据,并希望将其写入第二个文件。但我的程序返回错误:

1
sequence item 1: expected string, list found

这似乎是因为write()想要一个字符串,但它正在接收一个列表。

那么,对于这段代码,我如何将列表buffer转换为字符串,以便将buffer的内容保存到file2中?

1
2
3
4
5
6
7
8
9
10
11
12
13
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()


str.join试试:

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

文档说:

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


1
''.join(buffer)


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

将"给","B","C""输出


1
file2.write( str(buffer) )

解释:str(anything)任何Python对象将转换为它的字符串表示形式。你得到的类似的输出,但如果你的print(anything),字符串。

注意:这可能是不是你想要的,它已经在操作,控制单元(buffer在线如何在concatenated——它将放在每一个,-但它可能对别人有用。


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

方法1:

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

方法2:

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

方法3:

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


来自官方的FAQ是Python 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:

1
2
3
4
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):

1
2
3
result = bytearray()
for b in my_bytes_objects:
    result += b

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