繁体   English   中英

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"

如何将它们全部删除?

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

     body1 = body.replace("\n",'')
     body2 = body1.replace("\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 在您的情况下,您想不使用任何内容来“替换” new line '\\n' '' 如下所示

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

这将返回一个新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])\1+', '', body))

或全部删除:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM