我是 Python 的初学者,一直在尝试迄今为止所知道的内容,并遇到了以下问题。有人可以帮助我理解为什么会发生这种情况吗?假设我有一个名为“test.txt”的文本文件,其中包含以下内容,This is the first lineThis is the second lineThis is the third line我通过执行以下操作来打印此文本文件中的每一行,with open('test.txt', 'r') as f: for line in f: print(line)然而,我们得到的输出是,This is the first lineThis is the second lineThis is the third line如上所示,我们得到一个空行,因为文本文件中的每一行在每一行的末尾都包含一个“\n”。为了摆脱上面打印的空行,我知道我们可以这样做,with open('test.txt', 'r') as f: for line in f: print(line, end='')这给了我们以下输出,This is the first lineThis is the second lineThis is the third line我不明白的是,我们如何通过在每行末尾添加一个空字符串来摆脱换行符?Pythonpython-3.x细绳for循环这
2 回答
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
请注意,“\n”是赋予 的默认参数end
。这是来自官方 python 文档: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
。
您可以在此处查看文档:https ://docs.python.org/3/library/functions.html#print
墨色风雨
TA贡献1853条经验 获得超6个赞
python 中的函数的参数print
有一个默认值,当您用空字符串覆盖该值时=>您将删除新的行行为。\n
end
''
print(line, end='')
添加回答
举报
0/150
提交
取消