首页 文章

使用open时,Python不会对字符串进行适当的连接

提问于
浏览
1

我有一个简单的.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'))

但这是打印

enter image description here

那么字符串的其余部分发生了什么 . 因为打印教学是假的不是它 . 有人可以解释python的这种行为 . 谢谢

3 回答

  • 1

    您可能有一个带 '\r\n' 的Windows文件,而 rstrip 正在返回 \r ,这意味着该回车返回到行的开始并被覆盖 .

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

  • 0
    rstrip('\r\n')
    

    奇迹般有效 . 必须提到我在Ubuntu上,但它只在 '\n' 的Windows中工作 .

  • 0

    对我来说它也有效......但我使用的是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
    >>>
    

相关问题