1

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.

4
  • Just call str.rstrip() without arguments, it will clean all whitespaces (including newline). Commented Jan 23, 2022 at 18:37
  • @OlvinRoght Will it strip regular spaces too, though? I need those to stay in my text files... Commented Jan 23, 2022 at 18:46
  • Then call it with '\r\n' Commented Jan 23, 2022 at 18:50
  • rstrip removes the trailing whitespace at the end of the line, so you don't have to worry about it removing other whitespace characters. This is what's normally used to remove the '\n' and '\r\n' at the end of lines. Commented Jan 23, 2022 at 18:53

1 Answer 1

3

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.rstrip("\n", ""), end="")
Sign up to request clarification or add additional context in comments.

16 Comments

Thanks! It seems to have worked! I have no idea why this for loop worked while simple replace() didn't, but thanks a lot!
@Mymokol You can prevent print from adding a newline with end=''.
And no need to call readlines, you can just use for lines in test:.
@MarkRansom Oops, my bad. Thanks, I didn't know you could do that. I have fixed the post.
Answer is accepted, but it's wrong. To remove trailing char you should use .rstrip(), cause .replace() will iterate over all string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.