Python2和3版本对str和bytes类型的处理

时间:2023-03-08 17:15:25
Python2和3版本对str和bytes类型的处理

python2中字符串分为2种类型:

  • 字节类型:str,字节类型,通过decode()转化为unicode类型

  • unicode类型:unicode ,通过encode转化为str字节类型

  字节类型 和 unicode类型的转化:

    • 字节类型通过decode转化为unciode类型
    • unciode类型通过encode方法转化为直接类型
    • 方法的使用和python3相同,但是在方法中默认的编码方式为ascii, 对中文需要手动指定为utf-8

python3中字符串分为2种类型:

  • str:unicode,通过encode() 转化为bytes

  • bytes:字节类型,通过decode()转化为 str类型

1. str/bytes

  Python 3 所有的 strings 均是 unicode 类型。

  Python 2 将 strings 处理为原生的 bytes 类型,而不是 unicode。

# python3 中
# python3 中

>>> a = '中文'

>>> a
'中文' >>> type(a)
<class 'str'>
# python2中,由于a已经是字节类型,所以只能对其进行解码变为str类型,不能对其进行编码.(根据2.x版本不同,有时候也不能进行解码)
# python2中

>>> a = '中文'

>>> a
'\xd6\xd0\xce\xc4' >>> type(a)
<type 'str'> # 相当于 b"中文" 这个写法
>>> b = b"中文" >>> b
'\xd6\xd0\xce\xc4' >>> type(b)
<type 'str'>

2. str 与 bytes 之间的类型转换

str 与 bytes 之间的类型转换如下:

# str 与 bytes 之间的类型转换如下:
str -> bytes: bytes(s, encoding='utf8')
bytes -> str: str(b, encoding='utf-8') # 通过编码解码的形式对二者进行转换
str 编码成 bytes 格式: str.encode(s)
bytes 格式编码成 str 类型: bytes.decode(b)

另附: python str与bytes之间的转换

# bytes object
b = b"example" # str object
s = "example" # str to bytes
bytes(s, encoding = "utf8") # bytes to str
str(b, encoding = "utf-8") # an alternative method
# str to bytes
str.encode(s) # bytes to str
bytes.decode(b)