String to Bytes Python without change in encoding

前端 未结 2 2083
孤街浪徒
孤街浪徒 2020-12-10 06:19

I have this issue and I can\'t figure out how to solve it. I have this string:

data = \'\\xc4\\xb7\\x86\\x17\\xcd\'

When I tried to encode

2条回答
  •  天命终不由人
    2020-12-10 06:44

    You can use 'raw_unicode_escape' as your encoding:

    In [14]: bytes(data, 'raw_unicode_escape')
    Out[14]: b'\xc4\xb7\x86\x17\xcd'
    

    As mentioned in comments you can also pass the encoding directly to the encode method of your string.

    In [15]: data.encode("raw_unicode_escape")
    Out[15]: b'\xc4\xb7\x86\x17\xcd'
    

提交回复
热议问题