美文网首页
Python编码和解码

Python编码和解码

作者: 忆江南_1569 | 来源:发表于2017-12-10 10:30 被阅读55次

    decode

    解码

    s = '呵呵'
    sg = sg.encode('gbk')  # 将呵呵编码成gbk格式
    print(sg)
    s1 = sg.decode('gbk')  # 将呵呵使用gbk解码成unicode格式(使用什么方式编码就需要对应的方式解码)
    print(s1)
    # 这里如果sg使用utf-8解码会抛出UnicodeDecodeError
    s3 = sg.decode('utf-8')
    

    output:

    b'\xe5\x93\x88\xe5\x93\x88'
    呵呵
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte
    

    encode

    编码

    s = '哈哈'
    su = s.encode('utf-8')
    print(su)
    

    output:

    b'\xe5\x93\x88\xe5\x93\x88'  # utf-8格式的‘哈哈’
    

    encoding

    指定编码格式

    unicode

    unicode编码字符串可以表示更多的字符集,Python3中默认的字符串是unicode,unicode字符串可以编码成utf-8,gbk,gb2312等等,同样的utf-8.gbk,gb2312等字符串也可以解码成unicode字符串,unicode字符串可以当做一个中间转换的编码

    相关文章

      网友评论

          本文标题:Python编码和解码

          本文链接:https://www.haomeiwen.com/subject/fgumixtx.html