如何在Python中为字节字符串使用替换双反斜杠替换为单反斜杠 [英] How to use replace double backslashes to single one for byte string in Python

查看:502
本文介绍了如何在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

这篇关于如何在Python中为字节字符串使用替换双反斜杠替换为单反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆