如何将列表转换为字符串以在python中的输出txt文件中打印?

时间:2015-04-30 01:01:10

标签: python string list

我尝试使用它来将我的已排序数字列表转换为字符串,以便将其打印到输出txt文件。

clients = arping("192.168.1.*")
print clients

出于某种原因,它会创建一个输出文件,但它不会打印出我想要的内容,它会显示为空白。

我得到 output_str = ' '.join(str(e) for e in list) print("This is the text (string) that will be written on the output file") print(output_str) text_file = open("output.txt", "w") text_file.write(output_str) text_file.close() 从另一个线程,还有其他选择吗?我做错了吗?

4 个答案:

答案 0 :(得分:1)

您可以循环遍历列表并一次向文件写入一个字符(数字)。

text_file = open("output.txt", "w")
for num in list:
    text_file.write(str(num) + ' ')

text_file.close()

答案 1 :(得分:0)

询问代码行output_str = ' '.join(str(e) for e in list)的替代方法。您可以使用map将每个数字转换为str,然后使用join

 output_str = ' '.join(map(str, list_))

我建议将变量list重命名为list_,因为它是保留的关键字

答案 2 :(得分:0)

您正在迭代的变量实际上是list吗?因为有一个内置函数list可能会给你带来麻烦。我对你的代码略有不同:

>>> output_str = ' '.join(str(e) for e in [1,4,5,7,9])
>>> print("This is the text (string) that will be written on the output file")
This is the text (string) that will be written on the output file
>>> print(output_str)
1 4 5 7 9
>>> text_file = open("deleteme.txt", "w")
>>> text_file.write(output_str)
>>> text_file.close()

该文件确实包含了我的期望:

1 4 5 7 9

答案 3 :(得分:-1)

您可以尝试以下代码:

output_str = []
for e in list:
  output_str.append(str(e))
output = ''.join(output_str)

然后写入您的文件