Python中的string和bytes的转换

总的来说,bytes和string的关系是:

在这里插入图片描述

常见的几种编码及格式

  • utf8:形如\xe4\xbb\x8a\xe5\xa4
  • unicode:形如\u4eca\u5929\u5929\u6c14\u4e0d\u9519

注意:如果\变成了\说明,原字符串是编码后的格式,变成\是因为转换成了bytes
下面是几种常见的功能

string转bytes

s = "abc"       #string
s = "abc".encode()      #bytes,encode默认编码方式是utf-8
s = b"abc"      #bytes

bytes转string

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
s = b"abc"      #bytes
s = b"abc".decode()     #string,encode默认编码方式是utf-8
s = str(b"")    #string

bytes类型的unicode(中文)输出

s = '\\u4eca\\u5929\\u5929\\u6c14\\u4e0d\\u9519'        #中文是:今天天气真不错
new_s = s.encode().decode('unicode_escape')     #输出为:今天天气真不错
posted @ 2022-10-07 20:39  I'm_江河湖海  阅读(11)  评论(0)    收藏  举报