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