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

81 views Asked by At

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

3

There are 3 answers

9
RedX On BEST ANSWER

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

0
PythonProgrammi On

To me it works too... but I am using python 3, so I put the round brackets after print... but you used in line 7 and not in line 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'))

and this is the output:

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

works like a charm. Must mention I'm on a Ubuntu but it works in windows only with '\n' .