退出utf8解码('\x74'到't')

2024-06-16 12:59:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个字符串"\x00\x12\xf8\x05\x74\xa2",结果如下:

>>> s = "\x00\x12\xf8\x05\x74\xa2"
>>> s
'\x00\x12\xf8\x05t\xa2'
>>> print s
?t?
>>> print repr(s)
'\x00\x12\xf8\x05t\xa2'


>>> s = r"\x00\x12\xf8\x05\x74\xa2" <=== (I want this result but cannot use r'')
>>> s
'\\x00\\x12\\xf8\\x05\\x74\\xa2'
>>> print s
\x00\x12\xf8\x05\x74\xa2

您可以看到,字符串中的'\x74'在前半部分输出中自动转换为相应的utf8字符't'。我实际上有一个自定义字典做解码,所以我不想这个自动转换。在

如果我能在下半部分输出中保持字符串与r'string'相同,那就最好了。显然repr不起作用,有没有其他方法?在

更新:我想要这个,因为我需要将每个\xhh中的hh转换成int数。

提前谢谢。在


Tags: 字符串resultthisbutprintx00wantrepr
3条回答

可以手动创建所需的表示,如下所示:

>>> s = '\x00\x12\xf8\x05\x74\xa2'
>>> r = ''.join(['\\x%02x' % ord(b) for b in s])
>>> r
'\\x00\\x12\\xf8\\x05\\x74\\xa2'
>>> print r
\x00\x12\xf8\x05\x74\xa2

根据您的更新,如果您只想要ord值,请从我的原始答案中撕下一小块:

^{pr2}$

UPDATE: I want this because I need to convert hh in every \xhh into int number.

>>> s = "\x00\x12\xf8\x05\x74\xa2"
>>> [ord(x) for x in list(s)]
[0, 18, 248, 5, 116, 162]

I want this because I need to convert hh in every \xhh into int number.

In [17]: s = "\x00\x12\xf8\x05\x74\xa2"

In [18]: list(bytearray(s))
Out[18]: [0, 18, 248, 5, 116, 162]

您可能会对bytearray的用法感兴趣。在

相关问题 更多 >