如何在Python中为字节字符串使用替换双反斜杠替换为单反斜杠
我想用Python将字节串的双反斜杠替换为单反斜杠。
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'
我需要此字节字符串。
word = b'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'
如果我使用以下替换:
word = word.replace(b"\\",b"\")
我收到此错误。
File "test.py", line 79
word = word.replace(b"\\", b"\")
^
SyntaxError: EOL while scanning string literal
时EOL
有人知道怎么做吗?
Does anyone know how to do it?
\\
不是双反斜杠,而是一个逃脱了。看:
\\
is not double backslash but one escaped. Look:
print b'Z\xa6\x97\x86j2\x08q\\r\xca\xe6m'
# Z���jq\r��m
\r
(从您期望的输出中)不是2个字符而是一个:
And \r
(from your desired output) is not 2 chars but one:
print b'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'
# ��m�jq
(在将其打印到终端时,回车 \r
使我们无法看到第一个字母 Z
)
(When printing it to terminal, carriage return \r
prevents us from seen the first letter Z
)
如果您真的要用替换
,您可以这样做:'\\r'
'\r'
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
或者,如果您要替换所有转义序列 。 Python2版本:
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版本:
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