Take a closer look at the string, they are all single slash.
In [26]: my_str[0]
Out[26]: '\\'
In [27]: my_str[1]
Out[27]: 'x'
In [28]: len(my_str[0])
Out[28]: 1
And my_str.replace('\\','\')
won't work because the token here is \'
, which escapes '
and waits for the another closing '
.
Use my_str.replace('\\', '')
instead
Update: after few more days, I realize the following discussion may also be helpful. If the intension of a string with escape ('\\x'
or '\\u'
) are eventually hex/unicode literals, they can be decoded by escape_decode
.
import codecs
print(len(b'\x32'), b'\x32') # 1 hex literal, '\x32' == '2'
print(len(b'\\x32'), b'\\x32') # 4 chars including escapes
print(codecs.escape_decode('\\x32', 'hex')) # chars->literal, 4->1
# 1 b'2'
# 4 b'\\x32'
# (b'2', 4)
s = '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z'
ed, _ = codecs.escape_decode(s, 'hex')
print(len(s), s)
print(len(ed), ed)
# 49 \xa5\xc0\xe6aK\xf9\x80\xb1\xc8*$\xfbp(4\xd6{;Z
# 22 b'\xa5\xc0\xe6aK\xf9\x80\xb1\xc8*\x01\x12$\xfbp\x1e(4\xd6{;Z'