0

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."

dda
  • 6,030
  • 2
  • 25
  • 34
linderman
  • 149
  • 1
  • 9
  • 2
    There is not difference between an "EOL character" and `"\n"`. They are the same thing. The two-character string consisting of a back slash and the character "n" (Python reperesentation: `"\\n"` or `u"\n"`) is something different, but it won't be repleaced by `var.replace('\n', '')`. – Sven Marnach Jul 23 '12 at 12:23
  • 1
    If the text literally contains `\n`, it works fine: http://ideone.com/23367 – Felix Kling Jul 23 '12 at 12:24

1 Answers1

1
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.

Lanaru
  • 9,421
  • 7
  • 38
  • 64
  • Hi , thank you for the fast reply. Is it possible that Python 3.2 add automaticaly this r. Because i just tryed something: made txt file (under windows) and put there 3-4 paragraphs + random \n (literaly) inside them. Then i opened the file (r mode) and replaced all EOL (.replace('\n', 'ENDoFLINE')). Then i save it again When i open the file , the EOL are gone and the literaly typed \n are not touched. Which works great for me , but i wanted to know why replace('\n', 'ENDofLINE') replaces only the actual EOL chars and not the \n – linderman Jul 23 '12 at 13:07