【问题标题】: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?为什么在 Python 的 print 函数中传递给关键字参数 end 的参数在以下上下文中不能按预期工作?
【发布时间】:2021-01-20 03:32:19
【问题描述】:

我运行了以下代码,

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

【问题讨论】:

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

标签: python python-3.x text printing file-io


【解决方案1】:

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

例子:

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

【讨论】:

    【解决方案2】:

    文本文件的内容在每一行之后都有一个 \n,所以我建议您通过添加以下行将 '\n' 替换为 '':

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

    所以代码看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 2022-11-03
      • 2020-09-27
      • 2022-01-26
      • 2017-08-01
      • 2020-02-07
      • 1970-01-01
      • 2010-09-24
      相关资源
      最近更新 更多