Python 在与 open 一起使用时没有正确连接字符串

Python doesn't do proper concatenation of string while using with open

我有一个简单的 .txt 文件,例如有很多行

motorola phone
happy cows
teaching
school work
far far north
teaching
hello

现在我只想读取所有这些字符串并打印出来。因此,如果该行包含教学,我想打印 teaching is awesome 所以这是我的代码

with open("input.txt", "r") as fo:
    for line in fo:
        if "teaching" in line:
            line = line.rstrip('\n') + " is awesome"
            print line
        else:
            print(line.rstrip('\n'))

但这是打印

所以字符串的其余部分发生了什么。因为假设打印教学很棒,不是吗?有人可以解释 python 的这种行为吗?谢谢

您可能有一个 windows 文件 '\r\n' 并且 rstrip 正在返回 \r 这意味着回车 returns 到该行的开头并且正在被覆盖。

尝试rstrip('\r').rstrip('\n')

对我来说它也有效...但我使用的是 python 3,所以我在打印后放置圆括号...但是您在第 7 行而不是第 5 行使用...? !

with open("input.txt", "r") as fo:
    for line in fo:
        if "teaching" in line:
            line = line.rstrip('\n') + " is awesome"
            print(line)
        else:
            print(line.rstrip('\n'))

这是输出:

motorola phone
happy cows
teaching is awesome
school work
far far north
teaching is awesome
hello
>>> 
rstrip('\r\n') 

很有魅力。必须提到我在 Ubuntu 但它在 windows 中仅适用于 '\n' .