gpt4 book ai didi

python - 如何从字节对象中删除双反斜杠 (`\\` )?

转载 作者:行者123 更新时间:2023-12-01 03:47:33 25 4
gpt4 key购买 nike

例如:

t = str.encode(msg)

print(t)

我收到双斜杠,如下所示:

b'\\xda\\xad\\x94\\xb4\\x0bg\\x92]R\\x9a1y\\x9d\\xed\\x04\\xd5\\x8e+\\x07\\xf8\\x03\\x1bm\\xd6\\x96\\x10\\xca80\\xe26\\x8a

但是,我想得到的结果是:

b'\xda\xad\x94\xb4\x0bg\x92]R\x9a1y\x9d\xed\x04\xd5\x8e+\x07\xf8\x03\x1bm\xd6\x96\x10\xca80\xe26\x8a'

如有任何帮助,我们将不胜感激。

最佳答案

利用 Python 文本编码

有些文本编码可以帮助您简单轻松地获得您想要的内容。
下面我进行编码和解码以获得所需的结果:

# I have the string shortened for presentation
your_string = "\\xda\\xad\\x94"

your_string.encode().decode('unicode_escape').encode("raw_unicode_escape")

上面所做的事情可以用三个简单的步骤来解释:

  1. 对字符串进行编码,以便将其转换为 bytes 对象,并稍后删除反斜杠转义序列。
  2. 使用 unicode_escacpe 编解码器将对象解码为字符串,以取消转义反斜杠。
  3. 使用 raw_unicode_escape 对对象进行编码,将其转回字节对象,无需额外转义。

多个反斜杠转义序列

也许您有一个带有多个反斜杠转义序列(或双反斜杠)的字符串。如果是这样,您只需根据需要多次重复上面列出的步骤 2 和 3 即可。

your_string = "\\\\xda\\\\xad\\\\x94"
your_string.encode().decode('unicode_escape').encode('raw_unicode_escape').decode('unicode_escape').encode('raw_unicode_escape')

这可能会变得非常乏味和困惑,但您始终可以创建一个函数来解决这个问题。

没有反斜杠转义序列

现在,如果您有一个不带任何反斜杠转义序列的字符串,并且想要将其转换为字节对象,则所需要做的就是步骤 1 中看到的编码:

your_string = "\xda\xad\x94"
your_string.encode()

字节对象

如果您有一个字节对象而不是字符串,则一切基本相同,只需跳过步骤 1,因为字节对象已经具有编码(否则会引发错误)。

your_bytes_obj = b"\\xda\\xad\\x94"
your_string.decode('unicode_escape').encode("raw_unicode_escape")

所有这些示例都应该为您提供一个没有转义反斜杠的对象字节,在我上面提供的示例中是:

b'\xda\xad\x94'
<小时/>

说明

unicode_escape 编解码器在解码时删除转义符(或者在编码时添加转义符),而 raw_unicode_escape 编解码器在编码时不会转义反斜杠。因此,在处理字节对象中的转义字符时,这两种编解码器都会派上用场。

raw_unicode_escape

Latin-1 encoding with \uXXXX and \UXXXXXXXX for other code points. Existing backslashes are not escaped in any way. It is used in the Python pickle protocol.

unicode_escape

Encoding suitable as the contents of a Unicode literal in ASCII-encoded Python source code, except that quotes are not escaped. Decode from Latin-1 source code. Beware that Python source code actually uses UTF-8 by default.

我想补充一点,str.encode() 方法并不是对字符串进行编码的唯一方法。或者,您可以使用 codecs 模块中的 encode 函数,甚至是内置的 bytes 函数(只需确保提供编码参数)。
我之所以在这里使用 str.encode 方法是因为它看起来更简单。

有关详细信息,请参阅:
Python 2 Library - Python Specific Encodings
Python 3 Library - Text Encodings
Python 3 Lexical Analysis - String & Bytes Literals and Escape Sequences

关于python - 如何从字节对象中删除双反斜杠 (`\\` )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38763771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com