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

版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/89217047

平时使用的都是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的值是一样的

猜你喜欢

转载自blog.csdn.net/mouday/article/details/89217047
今日推荐