【自学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 = 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。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年3月5日 下午2:28
下一篇 2023年3月5日 下午2:29

相关推荐