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

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)

参考: https://blog.csdn.net/lanchunhui/article/details/72681978

猜你喜欢

转载自www.cnblogs.com/yuanyongqiang/p/10646961.html