msg = "北京"
print(msg.encode(encoding = "utf-8"))#字符串转换为二进制数据(参数最好加上utf-8,若没有该参数,则为系统默认的参数,可能不是utf-8编码)
print(msg.encode(encoding = "utf-8").decode(encoding = "utf-8"))#二进制数据转换为字符串(参数最好加上utf-8,若没有该参数,则为系统默认的参数,可能不是utf-8编码)
结果:
b‘\xe5\x8c\x97\xe4\xba\xac‘
北京