Search code examples
pythongae-python27

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


I have a simple .txt file with bunch of lines for instance

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

now all I want to do is read all these strings and print out. So if the line contains teaching I want to print teaching is awesome so here is my code

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'))

But this is printing

enter image description here

so what is happening to the rest of the string. Because it is suppose to print teaching is awesome isn't it. Can some one explain this behaviour of python. Thanks


Solution

  • You probably have a windows file with '\r\n' and rstrip is returning \r which means the carriage returns to the beggining of the line and being overwritten.

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