python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python bytes转string

Python bytes转string实现方式

作者:i白

本文介绍了Python中使用str()函数和bytes的decode()函数将bytes类型转换为string类型的方法,并通过举例说明了具体操作步骤

Python string转bytes

Python 中,bytes 类型和 字符串 的所有操作、使用和内置方法也都基本一致。因此,我们也可以实现将 bytes 类型转换成 string 类型。

Python bytes转string方法

Python bytes 转 string 方法主要有两种方法:即使用 str() 函数将 bytes 转 string 和 使用 bytes 的 decode() 函数将 bytes 转 string。

案例

bytes对象转字符串

使用 str() 函数,将 bytes 序列转成字符串

print("嗨客网(www.haicoder.net)")

# 使用 str 函数,将 bytes 序列转成字符串
byteHaiCoder = b'Hello \xe5\x97\xa8\xe5\xae\xa2\xe7\xbd\x91(HaiCoder)!'
strHaiCoder = str(byteHaiCoder, 'utf-8')
print('strHaiCoder:', strHaiCoder)

程序运行后,控制台输出如下:

首先,我们在字符串 HaiCoder 前面加了字符 b,定义了一个 bytes 类型的 变量 byteHaiCoder。接着,使用 str() 函数,将 bytes 变量转换成 string 类型,并指定字符编码为 utf-8。

最后,使用 print() 函数,打印被转换后的字符串。

bytes对象转字符串

使用 decode() 函数,将 bytes 序列转成字符串。

print("嗨客网(www.haicoder.net)")

# 使用 decode 函数,将 bytes 序列转成字符串
byteHaiCoder = b'Hello \xe5\x97\xa8\xe5\xae\xa2\xe7\xbd\x91(HaiCoder)!'
strHaiCoder = byteHaiCoder.decode('utf-8')
print('strHaiCoder:', strHaiCoder)

程序运行后,控制台输出如下:

首先,我们在字符串 HaiCoder 前面加了字符 b,定义了一个 bytes 类型的变量 byteHaiCoder。接着,使用 decode() 函数,将 bytes 变量转换成 string 类型,并指定字符编码为 utf-8。

最后,使用 print() 函数,打印被转换后的字符串。

Python bytes转string总结

Python bytes 转 string 方法主要有两种方法,第一种是使用 str() 函数将 bytes 转 string,第二种是使用 bytes 的 decode() 函数将 bytes 转 string。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文