bytes字节和string转换

bytes字节通过decode解码为string格式

string通过encode编码为byte格式

msg = "我喜欢编程"
print(msg.encode()) #string编码为bytes字节  运行结果:b'\xe6\x88\x91\xe5\x96\x9c\xe6\xac\xa2\xe7\xbc\x96\xe7\xa8\x8b'
print(msg.encode().decode()) #bytes字节解码为string  运行结果:我喜欢编程

s = '老张测试TM'
s1 =s.encode(encoding='utf-8') # 编码成bytes二进制的格式
print(type(s1), s1)	# 类型不是字符串,虽然是单引号括起来,但是前面有b''
s2 = s1.decode(encoding='utf-8') # 再变成人能读懂的
print(type(s2), s2) 
# 函数,Python, xxx(), print\decode\encode\type 都是函数

字符串字符直接的转换方式

1、二进制(bytes)转换为人能看懂的(str):也就是bytes -> str,需要使用decode;
2、翻过来,当徐奥把人能看懂的str为了传输方便时,就需要:str -> bytes,需要使用encode。
3、也就是写入文件使用encode,写成人能看懂的,读取文件时用encode指定对应的语言,识别即可;
4、如果被读取的文件是一个二进制的文件,一般也不需要使用decode方法转成人能理解的。需要的话,再指定即可。


版权声明:本文为Liquor6原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。