例如,我有一个包含许多行的简单.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的这种行为吗?谢谢
发布于 2017-01-25 00:09:33
您可能有一个包含'\r\n'的windows文件,而rstrip返回\r,这意味着回车返回到行的乞求并被覆盖。
试试rstrip('\r').rstrip('\n')
发布于 2017-01-25 01:55:44
rstrip('\r\n') 就像一种护身符。必须指出的是,我使用的是Ubuntu,但它只能在windows下使用'\n'。
发布于 2017-01-25 00:21:08
对我来说也行得通。但是我使用的是python 3,所以我把圆括号放在print后面……但是您在第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
>>> https://stackoverflow.com/questions/41832600
复制相似问题