zoukankan      html  css  js  c++  java
  • Python:基础数据类型:bytes

    Python:基础数据类型---bytes

    由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节。如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes

    Python对bytes类型的数据用带b前缀的单引号或双引号表示:

    b1 = b'alex'
    print(b1,type(b1)
    
    b'alex' <class 'bytes'>

    要注意区分'ABC'b'ABC',前者是str,后者虽然内容显示得和前者一样,但bytes的每个字符都只占用一个字节。 

    字符串与bytes相互转换:

    s1 = 'alex'
    # str ---> bytes encode 编码
    b1 = s1.encode('utf-8')
    print(b1)
    # bytes---> str  decode 解码
    s2 = b1.decode('utf-8')
    print(s2)
    
    b'alex'
    alex

    指定编码转换:

    s1 = 'alex'
    b2 = s1.encode('gbk')
    s3 = b2.decode('gbk')
    print(b2)
    print(s3)
    
    b'alex'
    alex

    中文转换时,不同的编码不能直接转换报错如下

    s4 = '中国'
    b4 = s4.encode('utf-8')
    s5 = b4.decode('gbk')
    print(s5)
    
    UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 2: illegal multibyte sequence
    s4 = '中国'
    b4 = s4.encode('utf-8') # utf-8 bytes
    print(b4)
    b6 = b4.decode('utf-8') # utf-8 unicode
    print(b6)
    b7 = b6.encode('gbk')   # gbk  bytes
    print(b7)
    
    b'xe4xb8xadxe5x9bxbd'     #不同编码的bytes数据,长度不一样
    中国
    b'xd6xd0xb9xfa'
  • 相关阅读:
    Silverlight 皮肤的使用(二)
    EF Core – Temporal Table 时态表
    SQL Server – Schema
    SQL Server – Temporal Table 时态表
    EF Core – QueryFilter & Interception
    SQL Server – Work with JSON
    EF Core – Soft Delete 实现
    C# – 10.0
    ASP.NET Core – 读写 Request / Response
    ASP.NET Core – Middleware
  • 原文地址:https://www.cnblogs.com/bailo/p/9085172.html
Copyright © 2011-2022 走看看