[英]Unable to replace backslash from a string using replace function in python?
我正在尝试从 python 中的字符串中删除反斜杠。 我使用的代码如下:
vb='\x82\x81'
vb.replace('\\',"")
The output I am getting is the same string:
'\x82\x81'
The output I want is:
'x82x81'
您可以将变量定义为原始字符串:
>>> vb=r'\x82\x81'
>>> vb.replace('\\',"")
'x82x81'
由于答案解决了 OP 的问题,并且有人似乎对它的工作感到不安(感谢角落案例),因此在“来自文件或网络请求或其他任何内容的实际输入”的情况下,这里有一些其他解决方案(最后一个应该是最通用的):
>>> vb='\x82\x81'
>>> vb=repr(vb).strip("'")
>>> vb.replace('\\',"")
'x82x81'
在\\x09\\x0a\\x5c\\x61
等的情况下。
>>> vb='\x09\x0a\x5c\x61\x80\x08\x90\x00\x10\x01'
>>> ''.join([ hex(ord(b))[1:].zfill(3).replace('0x','x0') for b in vb ])
'x09x0ax5cx61x80x08x90x00x10x01'
是的,它很丑,但有效(虽然不能测试太多) - 可能有更简单的方法,嗯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.