Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extra newline output when using print() in Python

I am brand new to Python. I am reading text from a file & replacing a word. I simply want to output the same two lines, with the word replacement, where the first line ends with a newline.

ADAMS, Ernie, 166 Winterstreamrose Way
NEWLINE, None, 1 Nomorenewlines Street

My test code is:

# readFileLines.py  --- testing file line reading, replacing text & dealing with newlines

with open("line.txt") as f:
    for line in f:
        for word in line.split():
            if word == 'Way':
                line = line.replace("Way", "Street")
        print(line)

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ADAMS, Ernie, 166 Winterstreamrose Street

NEWLINE, None, 1 Nomorenewlines Street

Why do I get an extra newline between the output lines? I note, that like in line.txt, there is no newline after the second line of output.

Any suggestions appreciated.

>Solution :

When reading file with this idiom:

with open("line.txt") as f:
    for line in f:

The line comes with a \n character at the end.

Try this:

with open("line.txt") as f:
    for line in f:
        line = line.strip()  # Removes the "\n" character
        for word in line.split():
            if word == 'Way':
                line = line.replace("Way", "Street")
        print(line, end="\n") # Puts back the "\n" character.

Or you can use print(line, end=""). By default, print() ends with a \n char, you can specify the the end="" to be to avoid the extra newline with the line isn’t striped when reading, i.e.

with open("line.txt") as f:
    for line in f:
        for word in line.split():
            if word == 'Way':
                line = line.replace("Way", "Street")
        print(line, end="")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading