Replacing "\r\n" with "\n"

I would recommend using splitlines instead of a regex or search/replace

"\n".join(mytext.splitlines())

This is a solution to try if any of the above did not work (which was the case for me using the Anaconda Distribution of Python3).

mytext.replace("\\r\\n", "\\n")

This has to do with \ being used as an escape character. I thought that the above answers that used the raw string formatter would achieve the same thing, but for whatever reason that did not work for me, and this did.


mytext.replace(r"\r\n", r"\n")

The 'r' denotes a raw string, which tells python to interpret the backslashes in the text as literal characters and not as escape characters.


"\n".join(mytext.splitlines()) This works for me. mytext.replace(r"\r\n", r"\n"), this not work.

Tags:

Python