strip() 不替换所有 \n

strip() does not replace all \n

我正在尝试删除此字符串中的所有 "\n"。然而 string.strip() 方法并没有完全清除文本

body = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSome text\n\nHow toremovealln?\n\t\t\t\t\tbecause notworking\n\t\t\t\t\t"
body.strip("\n")

结果是

"Some text\n\nHow toremovealln?\n\t\t\t\t\tbecause notworking\n\t\t\t\t\t"

如何将它们全部删除?

使用string.replace将'\n'替换为''(空字符串):

body = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSome text\n\nHow toremovealln?\n\t\t\t\t\tbecause notworking\n\t\t\t\t\t"
print(body.replace('\n', ''))

使用 string.replace() 而不是 strip:

此方法将用新的 char 替换旧的 char。在你的情况下,你想要 'replace' new line '\n' 什么都没有 ''。如下所示

body.replace('\n', '')

这将 return 一个新的 string,您可以将其重新分配给正文:

body = body.replace('\n', '')

现在 body 是:

'Some textHow toremovealln?\t\t\t\t\tbecause notworking\t\t\t\t\t'

所以如果你最终想删除 tabs '\t' 你可以像上面所说的那样对它们做进一步的 string.replace():

body = body.replace('\t', '')

如果您只想删除 重复的 换行符,您可以通过 re.sub:

使用正则表达式
re.sub(r'([\n])+', '', body))

或全部删除:

re.sub(r'\n', '', body)

您有 '\n' 和 '\t' 分别被 '' 和 ' ' 替换。所以你可以使用

     body1 = body.replace("\n",'')
     body2 = body1.replace("\t",' ')