美文网首页
016_字符编码

016_字符编码

作者: Nzkalhbxx | 来源:发表于2017-10-16 21:53 被阅读0次
# __author__:Nzkalhbxx
# __date__:2017/10/16
# Python3中字符的默认编码标准是unicode, 而unicode是包容万象的, 因此当需要以特定格式编码时, 使用的是encode()
s = "PpPig大傻瓜啊"
# encode(self, encoding='utf-8', errors='strict'): 将字符以指定格式编码, 返回编码之后的字节类型
unicode_enconde_to_uft8 = s.encode("utf-8")
# unicode_enconde_to_gbk = s.encode("gbk")
print(s)

print("".join(["unicode to utf8: ", str(unicode_enconde_to_uft8]))
# print("".join(["unicode to gbk: ", str(unicode_enconde_to_gbk)]))

# decode(self, *args, **kwargs): 将字节类型以指定格式解码
s_decode_from_utf8 = unicode_enconde_to_uft8.decode("utf-8")
# s_decode_from_gbk = unicode_enconde_to_gbk.decode("gbk")

print(s_decode_from_utf8)
# print(s_decode_from_gbk)

"""将原本是以utf8编码的字节类型数据以gbk的规范解码, 会出现错误信息或者乱码,
    原因在于不同的编码格式对相同的字符处理方式是不一定相同的:
    当使用utf-8编码时, 中文占三个字节
    而当使用gbk编码时, 中文只占两个字节
    同样, 当使用utf的规范解码时, 当遇到以中文编码开始的字节类型时, 则取三个字节组成一个中文字符
    当使用gbk解码时, 当编码到其中的一个字节且在gbk编码表中是中文编码的开头的字节时, 则取两个字节组成一个中文字符
    所以当我们用utf-8编码, 而以gbk解码时, 遇到中文必然会出现乱码或者出错"""

print("".join(["unicode_enconde_to_uft8.decode(): ", str(unicode_enconde_to_uft8.decode("gbk"))]))
# print("".join(["unicode_enconde_to_gbk.decode(): ", str(unicode_enconde_to_gbk.decode("utf-8"))]))
运行结果

相关文章

  • 016_字符编码

  • 部分知识点

    chr(编码值) - 将字符编码转换成字符 ord(字符) - 获取字符对应的编码值 可以将字符编码放到字符串中便...

  • 字符编码知识梳理

    [toc] 字符编码: 字符编码(英语:Character encoding)、字集码是把字符集中的字符编码为指定...

  • Python正式课第十三天

    一、文件操作与字符编码 1. 字符编码 编码 将字符转换为对应的二进制序列的过程叫做字符编码(字符->二进制01)...

  • 字符编码

    一. 什么是字符编码? 字符编码(英语:Character encoding)也称字集码,是把字符集中的字符编码为...

  • python 高级方法

    Python的字符串类型 字符编码方法 查看Python中的字符串编码名称,查看系统的编码 源文件字符集编码声明:...

  • Java内存中的文本编码

    1、编码简介 1.1 概念简析:字符、字符集、编码字符集、Code Point、Code Unit和字符编码格式 ...

  • python 字符 编码 简述

    字符编码问题很简单,当你可以区分以下几种概念之后: 字节编码与字符编码 字节串与字符串 文件编码、IDE编码、其他...

  • 13.Python之字符编码

    Python之字符编码 字符编码字符编码记录的是二进制与文字的对应关系。 常见的字符编码ASCII码:包含英文字母...

  • 笔记-encode与decode

    字节串-->decode('原来的字符编码')-->Unicode字符串-->encode('新的字符编码')--...

网友评论

      本文标题:016_字符编码

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