[英]How to remove space followed by line break in python?
我有這個字符串: 'time. \\nAlthough'
'time. \\nAlthough'
我想做的是刪除所有空格,然后換行。 我嘗試了以下操作,但我沒有刪除任何內容:
phrase = """
time.
Although
"""
phrase = phrase.replace(' \n','')
print(phrase)
任何幫助將非常感激!
由於某些原因,您粘貼的字符串包含“不可見字符”。 要看到這一點,您可以在字符串上調用repr
:
phrase = """
time.
Although
"""
repr(phrase)
## >>> "'\\ntime. \\u200b\\n\\nAlthough'"
在線快速瀏覽顯示\\\
是一個“ 零寬度空格 ”。
您必須更改替換以將此因素考慮在內,或者首先弄清楚零寬度空間是如何進入字符串的。
phrase = phrase.replace(" \u200b\n", "")
print(phrase)
##
## time.
## Although
您可以使用:
import re
phrase = """
time.
Although
"""
phrase = re.sub(r"\s+$", "", phrase, 0, re.MULTILINE)
我認為您所期望的只是刪除\\n
(換行符)留在那里的空間。 如果是這樣,您可以嘗試以下代碼:
phrase = """
time.
Although
"""
phrase = phrase.replace(' \n','\n') # Leaving newline and removes the white space
print(phrase)
或者,如果您想單獨刪除以下換行符,則可以嘗試以下操作:
phrase = """
time.
Although
"""
phrase = phrase.replace('\n','') # Leaving newline and removes the white space
print(phrase)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.