Replace \n with

2019-01-13 12:45发布

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.

6条回答
Melony?
2楼-- · 2019-01-13 13:23

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

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

Hope this helps someone else!

查看更多
甜甜的少女心
3楼-- · 2019-01-13 13:25
thatLine = thatLine.replace('\n', '<br />')

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

查看更多
来,给爷笑一个
4楼-- · 2019-01-13 13:25

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

'<br />'.join(thatLine.splitlines())
查看更多
淡お忘
5楼-- · 2019-01-13 13:36

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

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

查看更多
欢心
6楼-- · 2019-01-13 13:39

Just for kicks, you could also do

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

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

查看更多
甜甜的少女心
7楼-- · 2019-01-13 13:40

You could also have problems if the string has <, > or & chars in it, etc. Pass it to cgi.escape() to deal with those.

http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape

查看更多
登录 后发表回答