Python字符串到字节的转换。双反斜杠问题 [英] Python-String to Bytes conversion. Double BackSlash issue

查看:713
本文介绍了Python字符串到字节的转换。双反斜杠问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了问题。我有这个字符串:

I've got a problem. I've this string:

a=O\x8c\x90\x05\xa1\xe2!\xbe

如果我使用:

c=str.encode(a)

这是结果:

b'O\\x8c\\x90\\x05\\xa1\\xe2!\\xbe'

我需要那些双反斜杠成为单反斜杠,而我确实需要该类型的数据为BYTES。我需要返回此值:

I need those double backslash to be single backslash and i really need that type of data to be BYTES. I need to return this:

c=b'0\x8c\x90\x05\xa1\xe2!\xbe'

然后键入(c)== bytes
有什么想法吗? / p>

And type(c)==bytes Any idea?

推荐答案

您可以使用 str.decode()并将其编码为 unicode-escape 。然后使用所需的编码对其进行解码,以获取您的bytes数组。示例-

You can use str.decode() with encoding as unicode-escape . Then decode it back using the required encoding to get back your bytes array. Example -

c = a.decode('unicode-escape').encode('<required encoding>')

演示-

>>> a
b'O\\x8c\\x90\\x05\\xa1\\xe2!\\xbe'
>>> c = a.decode('unicode-escape').encode('ISO-8859-1')
>>> c
b'O\x8c\x90\x05\xa1\xe2!\xbe'

这篇关于Python字符串到字节的转换。双反斜杠问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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