为什么在Python的print函数中传递给关键字参数end的参数在下面的上下文中不能正常工作?

为什么在Python的print函数中传递给关键字参数end的参数在下面的上下文中不能正常工作?,python,python-3.x,text,printing,file-io,Python,Python 3.x,Text,Printing,File Io,我运行了以下代码 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 lin

我运行了以下代码

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=' ')

文本文件的内容在每行后面都有一个“\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=" ")

在文件中,每行都有一个换行符。可以使用strip()函数将其删除

例如:

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

end=''
在打印的末尾添加一个空格。因此,您的脚本将读取以a\n结尾的行,并添加一个空格。
end='
您将在打印的末尾添加一个空格。因此,脚本将读取以\n结尾的行,并添加一个空格。