Question

I have a string similar to this:

Lorem ipsum '\n' ipsum lorem

And this is new paragraph.

I want to remove the EOL chars and these 2 paragraphs to become one line. BUT I dont want to affect the '\n' - which in this case is literally used (not as new line indicator).

If I just make:

var.replace('\n', '')

This will affect it as:

"Lorem ipsum '' ipsum loremAnd this is new paragraph."

And I want it to be:

"Lorem ipsum '\n' ipsum loremAnd this is new paragraph."

Was it helpful?

Solution

s = r'''
Lorem ipsum '\n' ipsum lorem

And this is new paragraph.
'''

print(s.replace('\n', ''))

->"Lorem ipsum '\n' ipsum loremAnd this is new paragraph."

Adding the 'r' when assigning the string to a variable tells python to interpret it as a raw string literal, meaning that it will see backslashes as literal backslashes and not as escape characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top