将列表转换为字符串 [英] Converting a list to a string
本文介绍了将列表转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从一个文件中提取了一些数据,并想将其写入第二个文件.但我的程序返回错误:
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
这似乎是因为 write()
想要一个字符串,但它正在接收一个列表.
This appears to be happening because write()
wants a string but it is receiving a list.
那么,关于这段代码,我如何将列表 buffer
转换为字符串,以便我可以将 buffer
的内容保存到 file2代码>?
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()
推荐答案
尝试 <代码>str.join:
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.
这篇关于将列表转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文