Python中字符串到Bytearray的转换

问题描述 投票:0回答:1

我有一个以下格式的字符串变量: var =“x14\x12\x13\x11\x69”

我的挑战是将这个字符串转换为字节数组以获得准确的结果: 字节数组(b'\x14\x12\x13\x11\x69')

expected_bytearry = bytearray(var, 'utf-8')

if i print(expected_bytearry), I get this result

bytearray(b'\\x14\\x12\\x13\\x11\\x69'). Which contains double backslash.

Another approach which I tried was expected_bytearryy = bytearray.fromhex(var.encode().hex())

with that, **I get bytearray(b'\x14\x12\x13\x11i')** **instead of bytearray(b'\\x14\\x12\\x13\\x11\\x69')**

I also tried:

b = bytearray(ord(c) for c in var)
a = bytearray(var, 'utf-8')

Both of them produced the same result of double backslash.

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

谢谢

python arrays byte string-conversion
1个回答
0
投票

这就是

unicode_escape
编码。所以你需要
decode
使用这种编码。

但不幸的是,你处于最糟糕的情况:解码是在字节字符串上完成的,并且你有一个字符串。并生成一个字符串,并且您需要一个字节数组。

因此出现了相当复杂的解决方案

var.encode().decode('unicode_escape').encode()
© www.soinside.com 2019 - 2024. All rights reserved.