![](/img/trans.png)
[英]Regex - Replace \\n and \n in string by <br> but not \\\\n
[英]Replace \n with <br />
我正在使用 Python 解析文件中的文本。 我必須將所有換行符 (\n) 替換為
因為此文本將構建 html 內容。 例如,這是文件中的一些行:
'title\n'
現在我這樣做:
thatLine.replace('\n', '<br />')
print thatLine
而且我仍然看到后面帶有換行符的文本。
thatLine = thatLine.replace('\n', '<br />')
str.replace() 返回字符串的副本,它不會修改您傳入的字符串。
只是為了踢,你也可以做
mytext = "<br />".join(mytext.split("\n"))
用<br />
替換字符串中的所有換行符。
出於某種原因使用 python3 我不得不轉義“\”-sign
somestring.replace('\\n', '')
希望這對其他人有幫助!
thatLine = thatLine.replace('\n', '<br />')
Python 中的字符串是不可變的。 您可能需要使用賦值運算符重新創建它。
如果字符串中包含<
、 >
或&
字符等,您也可能會遇到問題。將其傳遞給cgi.escape()
以處理這些問題。
http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape
問題是當您在replace()
調用中表示'\n'
時, '\n'
被視為由' \ n '
組成的String length=4
要擺脫這種情況,請使用 ascii 表示法。 http://www.asciitable.com/
例子:
newLine = chr(10)
thatLine=thatLine.replace(newLine , '<br />')
print(thatLine) #python3
print thatLine #python2
。
我知道這是一個舊線程,但我嘗試了建議的答案,不幸的是,簡單地用<br />
替換換行符並沒有做我需要的事情。 它只是將它們按字面意思呈現為文本。
一種解決方案是像這樣禁用自動轉義: {% autoescape false %}{{ mystring }}{% endautoescape %}
這可以正常工作,但如果您有用戶提供的內容,那就不好了。 所以這對我來說也不是一個解決方案。
所以這就是我使用的:
在 Python 中:
newvar = mystring.split('\n')
然后,將newvar
傳遞到我的 Jinja 模板中:
{% for line in newvar %}
<br />{{ line }}
{% endfor %}
如果您嘗試將字符串的 /n 替換為</br>
,我推測您想在 HTML 視圖中解析換行符。
word-break: break-all,
white-space: pre-wrap;
將這些添加到文本的父div/container
的樣式將解決您的問題,而無需任何字符串操作。
如果您想使用替換來執行此操作,並且
不適合您(就像我一樣),您可以使用以下內容:
text_to_split = r'Hello\n\n I am a test.'
split_text = text_to_split.replace('\\n', '\n')
您首先在示例文本中轉義 \,然后在替換文本中不轉義,它將生成一個新行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.