Python数据类型之py2与py3字符串类型区别

Python2.x字符串 VS Python3.x字符串

1. Python2.X的字符类型

1.1 str类型 & unicode类型

1
2
3
4
5
6
7
8
9
>>> s1 = '中'
>>> s2 = u'中'

# 分别看下s1与s2的类型
>>> print(type(s1))
<type 'str'>

>>> print(type(s2))
<type 'unicode'>

1.2 str类型与unicode类型的转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# utf-xxx是unicode字符集的具体编码形式,所以str类型转为unicode类型需要进行encode编码
>>> s1 = u'中'
>>> print(type(s1))
<type 'unicode'>
>>> new_s1 = s1.encode('utf8')
>>> print(type(new_s1))
<type 'str'>

# 反之,unicode类型转为str类型则是将unicode类型解码为str类型,用decode进行解码
>>> s2 = '中'
>>> print(type(s2))
<type 'str'>
>>> new_s2 = s2.decode('utf8')
>>> print(type(new_s1))
<type 'unicode'>

2. Python3.X的字符类型

2.1 str类型 & bytes类型

1
2
3
4
5
6
7
8
9
>>> s1 = 'yang'
>>> s2 = b'yang'

# 分别看下s1与s2的类型
>>> print(type(s1))
<class 'str'>

>>> print(type(s2))
<class 'bytes'>

2.2 str类型与bytes类型的转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 在python3.X中,str类型对应unicode数据,bytes类型对应bytes数据,文本都是unicode数据,对应str类型
# str类型转为bytes类型需要进行encode编码
>>> s1='yang'
>>> print(type(s1))
<class 'str'>
>>> new_s1 = s1.encode('utf8')
>>> print(type(new_s1))
<class 'bytes'>

# 反之,bytes类型转为str类型则是将unicode数据用decode进行解码
>>> s2=b'yang'
>>> print(type(s2))
<class 'bytes'>
>>> new_s2 = s2.decode('utf8')
>>> print(type(s2))
<class 'str'>

3. 总结

  • Python3.X最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分,不再会对bytes字节串进行自动解码。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。

  • Python3.X不会以任意隐式的方式混用str和bytes,正是这使得两者的区分特别清晰。用户不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然)。

  • 无论py2,还是py3,与明文直接对应的就是unicode数据,打印unicode数据就会显示相应的明文(包括英文和中文)

    • Python2.X中

      1
      2
      3
      4
      # str类型和unicode类型连接
      >>> print('Elijah'+u'Yang')

      ElijahYang
    • Python3.X中

      1
      2
      3
      4
      5
      6
      #字节串和unicode连接
      >>> print(b'Elijah'+'Yang')

      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: can't concat str to bytes