![](/img/trans.png)
[英]Regex - Replace \\n and \n in string by <br> but not \\\\n
[英]string is contain with newline symbol (\n), how to use regex to replace \n to \n?
我有一個字符串
test = " \n this \nis\n\nto learn \n\n\n regex \n in \n\n python."
我使用 re.sub 來查找和替換 \\n 到 \\n 但它不起作用
check = re.sub("\n", "\n", test)
預期結果:
this
is
to
learn
regex
in
python
還有另一個選項可以做與上面相同的操作,但是如果我與時間消耗進行比較,那么正則表達式將獲勝
另外一個選項
# I need to loop through every single word in the string plus it doesn't change
if I have data like this "\nthis\n\nis"
check = test.replace("\n", "\n")
您可以嘗試用\\n
替換所有空格\\s+
:
test = " \n this \nis\n\nto learn \n\n\n regex \n in \n\n python."
output = re.sub(r'\s+', '\n', test).strip()
print(output)
這打印:
this
is
to
learn
regex
in
python.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.