Python 编码进阶

Python 编码进阶

  1. 不同的编码格式 不能互相识别

  2. 数据在内存中全部以Unicode编码,当数据用于网络传输和存储硬盘 ,必须以非Unicode进行编码。

  3. 如果想把内存中的数据 通过网络传输,存储等 在Python 中 转为非Unicode 编码 方式:

    数据类型转换为 (bytes)

    b = 'hello'
    b = b'hello' 	#type(b) = class bytes	字符串的常用方法 bytes都有 
    
    s1 = '熊猫'
    s2 = s1.encode('utf-8')	#中文不能通过b的方法转换 需要使用encode()方法
    

    bytes转换为其他编码:

    b1 = '熊猫'
    b1 = b1.encode('utf-8')  #type(b1) = bytes
    s1 = b1.decode('utf-8')  #type(s1) = utf-8
    

    GBK 如何 转换为 UTF-8?

    所有编码 都和Unicode 有关 通过 先转为Unicode 再转为 需要的编码

    s1 = '熊猫'
    s1 = b'xd6xd0'
    s2 = s1.decode('gbk')
    b2 = s2.encode('utf-8')
    

    总结:

    bytes为什么存在 ? str --> bytes (Unicode --> 非 Unicode)

    gbk <--> utf-8

原文地址:https://www.cnblogs.com/pandaa/p/12031386.html