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.
Author by
Hanut
Updated on July 09, 2022Comments
-
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 over 13 yearsThanks 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 over 13 yearsDon't know about @Falmarri's answer being "more Pythonic", but it's more efficient and probably faster.
-
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 over 6 yearsWelcome to StackOverflow.
-
JJFord3 almost 5 yearsWould give +2. 5 stars!
-
Jordan almost 4 yearsIf you use double quotes around the \n, you would not have to escape it.
-
Bendemann about 2 yearsYou might still need to escape it even if using double quotes