簡體   English   中英

字符串包含換行符 (\\n),如何使用正則表達式將 \\n 替換為 \\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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM