decode()函数将参数字符串编码的一种编码格式转换为所需的编码格式。
Python 字节到字符串
要在Python中把 字节转换成字符串 ,使用decode()方法从一个字节对象中产生一个字符串。String decode()是一个内置的方法,它使用注册的编码解码器对字符串进行解码。
decode()方法需要一个参数,即编解码器utf-8。 它可以是其他编解码器,但我们将使用这个编解码器,因为它是标准的。
如果你使用utf-8编码会有帮助,因为它非常普遍,但你需要使用你的数据实际使用的编码。
语法
decode(encoding, error)
参数
encoding :编码参数定义了需要进行解码的编码。
error :错误 参数决定了在发生错误时如何处理,例如,"strict"会引发Unicode错误。
返回值
它从解码后的字符串中返回原始字符串。
例子
要从字节对象转换为字符串,请遵循以下两个步骤。
步骤1:将原始字符串转换为字节对象
这一步只有在你没有字节对象的情况下才有必要。如果你有一个字节对象,你就不需要执行这一步。
让我们首先将字符串编码为字节对象。
# app.py
str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode()
print(str2)
输出
python3 app.py
b'Hello and welcome to the world of pyth\xc3\xb6n!'
要检查str2的数据类型,请使用type()方法:
str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode('utf-8')
print(type(str2))
输出
<class 'bytes'>
你可以看到,我们现在有一个字节对象。现在,我们将把字节对象转换为字符串。
步骤2:将字节对象转换为字符串。
要将字节对象转换为原始字符串,请使用具有确切编码机制的decode()方法。我们使用utf-8风格的编码, 所以你也需要使用相同类型的解码。
# app.py
str1 = "Hello and welcome to the world of pythön!"
str2 = str1.encode('utf-8')
print(type(str2))
print(str2)
print('After converting from bytes to string')
str3 = str2.decode('utf-8')
print(type(str3))
print(str3)
输出
python3 app.py
<class 'bytes'>
b'Hello and welcome to the world of pyth\xc3\xb6n!'
After converting from bytes to string
<class 'str'>
Hello and welcome to the world of pythön!
你可以看到,decode()方法成功地将字节对象解码为String。
就这样了。