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.
For some reason using python3 I had to escape the "\"-sign
Hope this helps someone else!
Strings in Python are immutable. You might need to recreate it with the assignment operator.
To handle many newline delimiters, including character combinations like
\r\n
, use splitlines (see this related post) use the following:thatLine = thatLine.replace('\n', '<br />')
str.replace() returns a copy of the string, it doesn't modify the string you pass in.
Just for kicks, you could also do
to replace all newlines in a string with
<br />
.You could also have problems if the string has
<
,>
or&
chars in it, etc. Pass it tocgi.escape()
to deal with those.http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape