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

erase a linebreak from a string in python

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.

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

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 lines in test.readlines():
        print(lines.replace("\n", ""))

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

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