python字符串与bytes的转换

python yekong 1402℃

比特类型

二进制的数据流--bytes
一种特殊的字符串
字符串前+b标记

bt = b'hello word'
print(type(bt))
结果
<class 'bytes'>

字符串转bytes的函数

encode

将字符串类型转为比特类型
用法
string.encode(encoding='utf-8',errors='strict')
参数
encoding:转换成的编码格式,默认utf-8
errors 出错时的处理方法,默认strict,直接抛出错误,也可以选择ignore忽略错误。
返回值
返回一个比特类型

data = 'python is a good code'
b_data = data.encode('utf-8')
print(b_data)
结果
b'python is a good code'

decode

将比特类型转为字符串
用法
bytes.decode(encoding='utf-8',errors='strict')
参数
encoding:转换成的编码格式,默认utf-8
errors 出错时的处理方法,默认strict,直接抛出错误,也可以选择ignore忽略错误。
返回值
返回一个字符串类型

byte_data = b'python is a good code'
str_data = byte_data.decode('utf-8')
print(str_data)
结果
python is a good code
喜欢 (2)