Python string转bytes教程
在
Python string转bytes方法
如果字符串内容都是 ASCII 字符,则可以通过直接在字符串之前添加字符 b 来构建字节串值。直接调用 bytes() 函数,将字符串按指定字符集转换成字节串,同时需要指定使用的字符集。
调用字符串本身的
案例
字符串转 bytes 对象
使用字符 b 修饰,将字符串转成 bytes 序列
print("嗨客网(www.haicoder.net)")
# 使用字符 b 修饰,将字符串转成 bytes 序列
name = b'HaiCoder'
print('Name:', name, 'Type:', type(name))
程序运行后,控制台输出如下:
首先,我们在字符串 HaiCoder 前面加了字符 b,定义了一个 bytes 类型的
字符串转 bytes 对象
使用 bytes 函数,将字符串转成 bytes 序列
print("嗨客网(www.haicoder.net)")
# 使用 bytes 函数,将字符串转成 bytes 序列
cname = '嗨客网(www.haicoder.net)'
bcname = bytes(cname, encoding='utf-8')
print('bcname:', bcname, 'Type:', type(bcname))
程序运行后,控制台输出如下:
首先,我们定义了一个字符串变量 cname,并给其赋值为 嗨客网(www.haicoder.net)。接着,我们使用 bytes() 函数将字符串变量 cname 转换成了 bytes 类型,同时设置转换使用的字符编码为 utf-8。
最后,我们使用 print 函数,打印转换后的变量的值和类型。
字符串转 bytes 对象
使用 encode 函数,将字符串转成 bytes 序列
print("嗨客网(www.haicoder.net)")
# 使用 encode 函数,将字符串转成 bytes 序列
cname = '嗨客网(www.haicoder.net)'
bcname = cname.encode('utf-8')
print('bcname:', bcname, 'Type:', type(bcname))
程序运行后,控制台输出如下:
首先,我们定义了一个字符串变量 cname,并给其赋值为 嗨客网(www.haicoder.net)。接着,我们使用 encode() 函数将字符串变量 cname 转换成了 bytes类型,同时设置转换使用的字符编码为 utf-8。
最后,我们使用 print 函数,打印转换后的变量的值和类型。
Python string转bytes总结
Python3 新增了 string 转 bytes,用于代表字节序列。
字符串(string) 是一串字符组成的序列,字符串处理的基本单位是字符,string 转 bytes 是一串字节组成的序列,bytes 类型处理的基本单位是字节。