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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:01:22  来源:igfitidea点击:

'str' object has no attribute 'decode'

pythonstringpython-3.xbinaryhex

提问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 orlp

Use binascii:

使用binascii

import binascii

binary_string = binascii.unhexlify(hex_string)

回答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 hexas 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 bytesobject.

无论哪种方式,你都会得到一个bytes对象。