Python使用 - 字符串和二进制的转换

发布时间 2023-07-26 23:06:12作者: yanghui01

字符串和二进制的转换,需要用到编码(比如:utf-8, gbk),它起到的主要作用:

1) 字符转二进制时:根据字符,去编码表查询该字符的二进制值

2) 二进制转字符时:根据二进制值,去编码表查询该二进制对应的字符

 

# 字符转二进制,也叫编码
str_bytes = "123abc中文".encode("gbk")
print(type(str_bytes), str_bytes) # <class 'bytes'> b'123abc\xd6\xd0\xce\xc4'

# 二进制转字符,也叫解码
a = str_bytes.decode("gbk") # <class 'str'> 123abc中文
print(type(a), a)

# 字符转二进制(bytes类方式)
str_bytes = bytes("123abc中文", "gbk")
print(type(str_bytes), str_bytes)

# 字符转二进制(b开头字符串方式)
str_bytes = b"123abc" # 不能有中文, 否则会抛异常 print(type(str_bytes), str_bytes) # <class 'bytes'> b'123abc'

 

参考

Python decode()方法 | 菜鸟教程 (runoob.com)

Python字符串开头的b"、u"、r"与中文乱码(摘) - 知乎 (zhihu.com)