在 Python 3 中解码十六进制字符串 [英] Decode Hex String in Python 3

查看:101
本文介绍了在 Python 3 中解码十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2 中,将字符串的十六进制形式转换为相应的 unicode 非常简单:

comments.decode("hex")

其中变量comments"是文件中一行的一部分(该行的其余部分不需要转换,因为它仅以 ASCII 表示.

然而,现在在 Python 3 中,这不起作用(我假设是因为字节/字符串与字符串/unicode 开关.我觉得 Python 3 中应该有一个单行代码来做同样的事情,而不是将整行读取为一系列字节(我不想这样做),然后分别转换该行的每一部分.如果可能,我想将整行读取为 unicode 字符串(因为该行的其余部分是 unicode),并且仅将这一部分从十六进制表示转换.

解决方案

类似:

<预><代码>>>>bytes.fromhex('4a4b4c').decode('utf-8')'JKL'

只需输入您使用的实际编码即可.

In Python 2, converting the hexadecimal form of a string into the corresponding unicode was straightforward:

comments.decode("hex")

where the variable 'comments' is a part of a line in a file (the rest of the line does not need to be converted, as it is represented only in ASCII.

Now in Python 3, however, this doesn't work (I assume because of the bytes/string vs. string/unicode switch. I feel like there should be a one-liner in Python 3 to do the same thing, rather than reading the entire line as a series of bytes (which I don't want to do) and then converting each part of the line separately. If it's possible, I'd like to read the entire line as a unicode string (because the rest of the line is in unicode) and only convert this one part from a hexadecimal representation.

解决方案

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'

Just put the actual encoding you are using.

这篇关于在 Python 3 中解码十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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