【自学Python】Python bytes转string
Python 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 = bHello xe5x97xa8xe5xaexa2xe7xbdx91(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 = bHello xe5x97xa8xe5xaexa2xe7xbdx91(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。
下一篇:
黑马javaweb综合案例---删除