Python 'str' 对象没有属性 'decode'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29030725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'str' object has no attribute 'decode'
提问by rao
I'm trying to decode hex string to binary values. I found this below command on internet to get it done,
我正在尝试将十六进制字符串解码为二进制值。我在互联网上找到了以下命令来完成它,
string_bin = string_1.decode('hex')
but I got error saying
但我有错误说
'str' object has no attrubute 'decode'
I'm using python v3.4.1
我正在使用 python v3.4.1
回答by Martijn Pieters
You cannot decode string objects; they are alreadydecoded. You'll have to use a different method.
你不能解码字符串对象;它们已经被解码。您将不得不使用不同的方法。
You can use the codecs.decode()
functionto apply hex
as a codec:
您可以使用该codecs.decode()
功能应用hex
的编解码器:
>>> import codecs
>>> codecs.decode('ab', 'hex')
b'\xab'
This applies a Binary transformcodec; it is the equivalent of using the base64.b16decode()
function, with the input string converted to uppercase:
这适用于二进制转换编解码器;它等效于使用base64.b16decode()
函数,输入字符串转换为大写:
>>> import base64
>>> base64.b16decode('AB')
b'\xab'
You can also use the binascii.unhexlify()
functionto 'decode' a sequence of hex digits to bytes:
您还可以使用该binascii.unhexlify()
函数将十六进制数字序列“解码”为字节:
>>> import binascii
>>> binascii.unhexlify('ab')
b'\xab'
Either way, you'll get a bytes
object.
无论哪种方式,你都会得到一个bytes
对象。