我是 Python 的初学者,一直在尝试迄今为止所知道的内容,并遇到了以下问题。有人可以帮助我理解为什么会发生这种情况吗?
假设我有一个名为“test.txt”的文本文件,其中包含以下内容,
This is the first line
This is the second line
This is the third line
我通过执行以下操作来打印此文本文件中的每一行,
with open('test.txt', 'r') as f:
for line in f:
print(line)
然而,我们得到的输出是,
This is the first line
This is the second line
This is the third line
如上所示,我们得到一个空行,因为文本文件中的每一行在每一行的末尾都包含一个“\n”。
为了摆脱上面打印的空行,我知道我们可以这样做,
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
我不明白的是,我们如何通过在每行末尾添加一个空字符串来摆脱换行符?
Pythonpython-3.x细绳for循环这
蝴蝶不菲
墨色风雨
相关分类