Python编程:Python2 和 Python3的字符串字典取值和MD5比较

简介: Python编程:Python2 和 Python3的字符串字典取值和MD5比较

平时使用的都是Python2,所以这个编码问题一直困扰着我,祝大家早日升级Python3


python2 和 python3的字符串类型


# 3.6.0
>>> type("你好")
<class 'str'>
# 2.7.5
>>> type("你好")
<type 'str'>
# 引入新特性之后
>>> from __future__ import unicode_literals, print_function
>>> type("你好")
<type 'unicode'>

以下代码在 python2.7.5 环境下测试


关于字典取值

>>> dct = {"key": "value", "键": "值"}
>>> dct["key"]
'value'
>>> dct["键"]
'\xe5\x80\xbc'
# 引入新特新后 直接取值报错了
>>> from __future__ import unicode_literals, print_function
>>> dct["键"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: u'\u952e'
>>> dct[u"键"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: u'\u952e'
# 将unicode对象 变码转为str对象
>>> dct["键".encode("utf-8")]
'\xe5\x80\xbc'
# 重新定义dict 取出的值也是unicode编码
>>> dct = {"key": "value", "键": "值"}
>>> dct["键"]
u'\u503c'
>>> dct[u"键"]
u'\u503c'

关于md5


>>> import hashlib
>>> s = "你好"
>>> s
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> hashlib.md5(s).hexdigest()
'7eca689f0d3389d9dea66ae112e5cfd7'
# 引入新特新后对原有的字符串没有影响
>>> from __future__ import unicode_literals, print_function
>>> hashlib.md5(s).hexdigest()
'7eca689f0d3389d9dea66ae112e5cfd7'
# 重新定义字符串,发现编码也变了
>>> s = "你好"
>>> s
u'\u4f60\u597d'
# 在新特新下要编码之后才能进行md5
>>> hashlib.md5(s).hexdigest()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>> hashlib.md5(s.encode("utf-8")).hexdigest()
'7eca689f0d3389d9dea66ae112e5cfd7'

就是说在ASCII 码下做MD5 和 unicode下做MD5的值是一样的

相关文章
|
2天前
|
存储 Python
python将字典的键或值解包到变量中
【7月更文挑战第5天】
12 4
|
2天前
|
Python
|
3天前
|
Python
Python中字典 直接解包
【7月更文挑战第4天】
10 3
|
2天前
|
Python
python解包字典到函数参数
【7月更文挑战第5天】
6 2
|
3天前
|
Python
Python中字典解包使用*和**操作符
【7月更文挑战第4天】
9 3
|
2天前
|
Python
python解包字典到新的字典
【7月更文挑战第5天】
10 1
|
3天前
|
Python
Python中字典解包解包到变量
【7月更文挑战第4天】
9 1
|
5天前
|
Python
Python中的解包字典
【7月更文挑战第2天】
5 1
|
9天前
|
Python
Python中字典解包
【6月更文挑战第21天】
12 2
|
10天前
|
存储 索引 Python
字符串、列表、元组、字典(python)
字符串、列表、元组、字典(python)