Replace \n with <br />

147,495

Solution 1

Just for kicks, you could also do

mytext = "<br />".join(mytext.split("\n"))

to replace all newlines in a string with <br />.

Solution 2

thatLine = thatLine.replace('\n', '<br />')

str.replace() returns a copy of the string, it doesn't modify the string you pass in.

Solution 3

For some reason using python3 I had to escape the "\"-sign

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

Hope this helps someone else!

Solution 4

To handle many newline delimiters, including character combinations like \r\n, use splitlines (see this related post) use the following:

'<br />'.join(thatLine.splitlines())

Solution 5

thatLine = thatLine.replace('\n', '<br />')

Strings in Python are immutable. You might need to recreate it with the assignment operator.

Share:
147,495
Hanut
Author by

Hanut

Updated on July 09, 2022

Comments

  • Hanut
    Hanut almost 2 years

    I'm parsing text from file with Python. I have to replace all newlines (\n) with
    cause this text will build html-content. For example, here is some line from file:

    'title\n'
    

    Now I do:

    thatLine.replace('\n', '<br />')
    print thatLine
    

    And I still see the text with newline after it.

  • Tim Pietzcker
    Tim Pietzcker over 13 years
    Thanks for accepting this, but please accept @Falmarri's answer instead. It's much more Pythonic. This here is more of a funny, backwards way of doing it. Not really recommended...
  • martineau
    martineau over 13 years
    Don't know about @Falmarri's answer being "more Pythonic", but it's more efficient and probably faster.
  • Tim Pietzcker
    Tim Pietzcker over 13 years
    @martineau: I meant this in the sense of "There should be one -- and preferably only one -- obvious way to do it.". And I'm pretty sure that mine isn't the one.
  • Cecil Curry
    Cecil Curry over 6 years
    Welcome to StackOverflow.
  • JJFord3
    JJFord3 almost 5 years
    Would give +2. 5 stars!
  • Jordan
    Jordan almost 4 years
    If you use double quotes around the \n, you would not have to escape it.
  • Bendemann
    Bendemann about 2 years
    You might still need to escape it even if using double quotes