【问题标题】:How do I convert a list into a string for printing in an output txt file in python?如何将列表转换为字符串以在 python 的输出 txt 文件中打印?
【发布时间】:2015-07-09 12:53:28
【问题描述】:

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

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

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

我收到了output_str = ' '.join(str(e) for e in list) 从另一个线程,有没有其他选择?我做错了吗?

【问题讨论】:

  • 它是否在写入上方的打印行上打印了正确的字符串?
  • 您不应该将变量命名为list,它是保留关键字。你能顺便打印一下它的内容吗?
  • 只要列表中有内容,您的代码就可以正常工作。 @ericrenouf 有一个很好的问题。愿意回答吗?

标签: python string list


【解决方案1】:

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

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

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

【讨论】:

  • 为什么您认为字符串转换会有所帮助? OP 没有提及异常。
  • @tdelaney @IgnacioVazquez-Abrams 他询问了他的代码行output_str = ' '.join(str(e) for e in list) 的替代方案。
【解决方案2】:

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

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

text_file.close()

【讨论】:

  • 我会使用here 记录的“with open”,我会从 list 更改列表名称,但这是迄今为止我见过的最佳答案。
  • @IgnacioVazquez-Abrams 道歉 - 已编辑以添加数字之间的空格。
  • @JGreenwell 你是对的 with open 声明。我忽略了这一点。谢谢!
  • 如果 OPs 代码不起作用,这不是问题的解决方案,这不会解决它。
【解决方案3】:

您正在迭代的变量实际上是否称为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

【讨论】:

  • 使用名为 list 的变量有风险,但不会对 OP 发布的代码造成任何问题。
【解决方案4】:

你可以试试这个代码:

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

然后写入你的文件

【讨论】:

  • 为什么你认为这比提问者已经拥有的更好?
  • OP 没有提到任何例外。这对修复代码没有任何作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
相关资源
最近更新 更多