您当前的位置: 首页 >  彭世瑜 Python

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

彭世瑜 发布时间:2019-04-11 18:18:56 ,浏览量:2

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

python2 和 python3的字符串类型

# 3.6.0
>>> type("你好")



# 2.7.5
>>> type("你好")


# 引入新特性之后
>>> from __future__ import unicode_literals, print_function
>>> type("你好")

以下代码在 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 "", line 1, in 
KeyError: u'\u952e'

>>> dct[u"键"]
Traceback (most recent call last):
  File "", line 1, in 
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 "", line 1, in 
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的值是一样的

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 2浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0550s