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月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
209 1
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
343 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
465 99
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
3月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
3月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
3月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
4月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
306 92
|
2月前
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
182 4
|
3月前
|
存储 JSON 数据管理
Python字典:高效数据管理的瑞士军刀
Python字典基于哈希表实现,提供接近O(1)的高效查找,支持增删改查、遍历、合并等丰富操作,广泛应用于计数、缓存、配置管理及JSON处理。其灵活性与性能使其成为数据处理的核心工具。
530 0

推荐镜像

更多