繁体   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