[SOLVED] erase a linebreak from a string in python

Issue

I’m working with .txt files in python.

I have linebreaks in the text files. Example:

line1
line2

I need to get rid of those linebreaks for my code to work.

I tried everything: text.replace("\n", ""), when that didn’t work, I wrote out the ord() of every character in the string and found out the linebreak character was 10, so I tried text.replace(chr(10), ""), when even that didn’t work, I even got to the point of writing a terrible for cycle, out of despair, to replace the chars, whose ord() == 10, with an empty string.

Nothing works.

Please help, I really need to get rid of those linebreaks.

I’m desperate.

Thank you.

Edit: I need regular spaces (" ") to stay in my text files.

Solution

The replace function should work, I’m not sure why it didn’t work for you:

with open("test.txt", "r") as test:
    for line in test:
        print(line.replace("\n", ""))

NOTE: Since Python prints a newline character when using the print function, it will appear as if the newlines are still there.

Answered By – Didlly

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *