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的值是一样的

相关文章
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
328 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
443 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:现代编程的首选语言
291 102
|
3月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
314 104
|
3月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
262 103
|
2月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
179 3
|
2月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
436 3

推荐镜像

更多