stringreplacenewlinepython-2.x

Replace '\n' in a string in Python 2.7


This is my file.txt:

Egg and Bacon;
Egg, sausage and Bacon
Egg and Spam;
Spam Egg Sausage and Spam;
Egg, Bacon and Spam;

I wanna convert the newLine '\n' to ' $ '. I just used:

f = open(fileName)
text = f.read()      
text = text.replace('\n',' $ ')
print(text)

This is my output:

$ Spam Egg Sausage and Spam;

and my output must be like:

Egg and Bacon; $ Egg, sausage and Bacon $ Egg ...

What am I doing wrong? I'm using #-*- encoding: utf-8 -*-

Thank you.


Solution

  • It is possible that your newlines are represented as \r\n. In order to replace them you should do:

    text.replace('\r\n', ' $ ')
    

    For a portable solution that works on both UNIX-like systems (which uses \n) and Windows (which uses \r\n), you can substitute the text using a regex:

    >>> import re
    >>> re.sub('\r?\n', ' $ ', 'a\r\nb\r\nc')
    'a $ b $ c'
    >>> re.sub('\r?\n', ' $ ', 'a\nb\nc')
    'a $ b $ c'