簡體   English   中英

如何將列表轉換為字符串以在python的輸出txt文件中打印?

[英]How do I convert a list into a string for printing in an output txt file in python?

我嘗試使用此命令將我的排序數字列表轉換為字符串,以便可以將其打印到輸出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) ,還有其他選擇嗎? 難道我做錯了什么?

您可以循環瀏覽列表,一次將一個字符(數字)寫入文件。

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

text_file.close()

詢問代碼行的替代方法output_str = ' '.join(str(e) for e in list) 您可以使用map將每個數字轉換為str,然后使用join

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

我建議將您的變量list重命名為list_因為它是保留關鍵字

您要遍歷的變量實際上稱為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

您可以嘗試以下代碼:

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

然后寫在你的文件中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM