如何删除 space 后跟 python 中的换行符?

How to remove space followed by line break in python?

我有这个字符串:'time. \nAlthough'

我想做的是删除所有空格,然后是换行符。我尝试了以下但我的它没有删除任何东西:

phrase = """
time. ​

Although 
"""

phrase = phrase.replace(' \n','')
print(phrase)

如有任何帮助,我们将不胜感激!

我认为您所期望的只是删除 space,留下 \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)

出于某种原因,您粘贴的字符串包含 "invisible character"。要查看此内容,您可以在字符串上调用 repr

phrase = """
time. ​

Although 
"""
repr(phrase)
## >>> "'\ntime. \u200b\n\nAlthough'"

在线快速浏览显示 \u200b 是一个“zero-width-space”。

您必须更改您的替换以考虑到这一点,或者首先弄清楚零宽度-space 是如何进入您的字符串的。

phrase = phrase.replace(" \u200b\n", "")
print(phrase)
## 
## time.
## Although

您可以使用:

import re
phrase = """
time. 

Although 
"""
phrase = re.sub(r"\s+$", "", phrase, 0, re.MULTILINE)

解释: