Python-String to Bytes conversion. Double BackSlash issue

自作多情 提交于 2019-12-18 13:25:19

问题


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

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

If i use:

c=str.encode(a)

This is the result:

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

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'

And type(c)==bytes Any idea?


回答1:


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>')

Demo -

>>> 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'


来源:https://stackoverflow.com/questions/33257875/python-string-to-bytes-conversion-double-backslash-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!