Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use replace double backslashes to single one for byte string in Python

Tags:

python

byte

I want to replace double backslashes to single one for byte string in Python.

For example, there is a bytes string.

word = b'Z\xa6\x97\x86j2\x08q\\r\xca\xe6m'

I need this bytes string.

word = b'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'

If I use replace like:

word = word.replace(b"\\",b"\")

I got this error.

File "test.py", line 79
word = word.replace(b"\\", b"\")
                               ^
SyntaxError: EOL while scanning string literal

Does anyone know how to do it?

like image 960
Atsushi Sakai Avatar asked Jan 28 '23 19:01

Atsushi Sakai


1 Answers

\\ is not double backslash but one escaped. Look:

print b'Z\xa6\x97\x86j2\x08q\\r\xca\xe6m'
# Z���jq\r��m

And \r (from your desired output) is not 2 chars but one:

print b'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'
# ��m�jq

(When printing it to terminal, carriage return \r prevents us from seen the first letter Z)

If you really want to replace '\\r' with '\r', you can do:

print repr(word.replace('\\r', '\r'))
# 'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'
print word.replace('\\r', '\r')
# ��m�jq

Or, if you want to replace all the escape sequences. Python2 version:

print repr(b'1\\t2\\n3'.decode('string_escape'))
# '1\t2\n3'
print b'1\\t2\\n3'.decode('string_escape')
# 1 2
# 3

Python3 version:

print(repr(b'1\\t2\\n3'.decode('unicode_escape')))
# '1\t2\n3'
print(b'1\\t2\\n3'.decode('unicode_escape'))
# 1 2
# 3
like image 108
Eugene Primako Avatar answered Jan 30 '23 10:01

Eugene Primako