Jack Slingerland Jack Slingerland -4 years ago 109
Python Question

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

I have some text data that is printing out the actual characters "\r\n" (so four characters total). I'd like to replace those four characters with the single "\n" character, but I can't seem to make Python do it for me. I'm currently trying:

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

But that just prints out "\n" (two characters, not one). I feel like I'm probably missing something obvious, but any help would be appreciated.

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download