簡體   English   中英

為什么在 Python 的打印函數中傳遞給關鍵字參數 end 的參數沒有在下面的上下文中按預期工作?

[英]Why does not the parameter passed to the keyword argument end in the print function of Python does not work as expected in the below context?

我運行了以下代碼,

with open('test.txt', 'r') as f:
    for line in f:
       print(line, end=' ')

我希望得到,

This is the first line This is the second line This is the third line

作為輸出。

相反,我得到了,

This is the first line
 This is the second line
 This is the third line 

有人能告訴我為什么會發生這種行為嗎?

.txt 文件中的內容如下,

This is the first line
This is the second line
This is the third line

文本文件的內容在每一行后都有一個 \\n,所以我建議您通過添加以下行將 '\\n' 替換為 '':

line = line.replace('\n', '')

所以代碼看起來像這樣:

with open('test.txt', 'r') as f:
for line in f:
   line = line.replace('\n', '')
   print(line, end=' ')

在文件中,每行都有一個換行符。 您可以使用 strip() 函數刪除它。

例子:

with open("test.txt", "r") as f:
     for line in f:
             print(line.strip(), end=" ")

暫無
暫無

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

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