转 - 使用from __future__ import unicode_literals时要注意的问题
原文链接:
http://www.cnblogs.com/ajianbeyourself/p/4471035.html
使用from __future__ import unicode_literals时要注意的问题
add by zhj: 在Python中有些库的接口要求参数必须是str类型字符串,有些接口要求参数必须是unicode类型字符串。对于str类型的字符串,调用len()和遍历时,其实都是以字节为单位的,这个太坑爹了,同一个字符使用不同的编码格式,长度往往是不同的。对unicode类型的字符串调用len()和遍历才是以字符为单位,这是我们所要的。另外,Django,Django REST framework的接口都是返回unicode类型的字符串。为了统一,我个人建议使用from __future__ import unicode_literals,将模块中显式出现的所有字符串转为unicode类型,不过,对于必须使用str字符串的地方要加以注意。关于字符串类型,也是Python2坑爹的地方
在py2.7的项目中用了__future__模块中的 unicode_literals 来为兼容py3.x做准备,今天遇到一个UnicodeEncodeError的错误,跟了下,发现这个小坑值得注意。是怎么样的一个坑呢?跟着代码看看。顺便深究一下原理。
1. 问题
未引用unicode_literals
#coding:utf-8
from datetime import datetime now = datetime.now()
print now.strftime('%m月%d日 %H:%M')
这段代码正常执行,输出: 03月12日 21:53
引入unicode_literals
#coding:utf-8
from __future__ import unicode_literals
from datetime import datetime now = datetime.now()
print now.strftime('%m月%d日 %H:%M')
抛出如下错误:
Traceback (most recent call last):
File "unicode_error_demo2.py", line 7, in <module>
print now.strftime('%m月%d日 %H:%M')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u6708' in position 2: ordinal not in range(128)
2. 原因分析
因为datetime.strftime()只接受str类型的字符串,不接受unicode类型的字符串。
3. 解决方案
方案一(推荐):传入str类型的参数
#coding:utf-8
from __future__ import unicode_literals
from datetime import datetime now = datetime.now()
print now.strftime('%m月%d日 %H:%M'.encode('utf-8')) # 指明str类型字符串
方案二(不推荐):设置运行时编码为utf-8

#coding:utf-8
from __future__ import unicode_literals
import sys
from datetime import datetime reload(sys)
sys.setdefaultencoding('utf-8') now = datetime.now()
print now.strftime('%m月%d日 %H:%M')

参考资料:
- 由__future__中unicode_literals引起的错误来研究python中的编码问题
- 黄聪:解决python中文处理乱码,先要弄懂“字符”和“字节”的差别
- http://docs.python.org/2/library/datetime.html#datetime.date.strftime
- http://docs.python.org/2.7/library/functions.html#getattr
- http://docs.python.org/2/whatsnew/2.6.html?highlight=bytestring#pep-3112-byte-literals
- http://www.cnblogs.com/huxi/articles/1897271.html
- http://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal
转 - 使用from __future__ import unicode_literals时要注意的问题的更多相关文章
- 使用from __future__ import unicode_literals时要注意的问题
add by zhj: 在Python中有些库的接口要求参数必须是str类型字符串,有些接口要求参数必须是unicode类型字符串.对于str类型的字符串,调用len()和遍历时,其实都是以字节为单位 ...
- 转 from __future__ import unicode_literals
转自 https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868200230 ...
- from __future__ import unicode_literals, absolute_import
Q:python模块中的相对导入,绝对导入,有些地方会写 from __future__ import absolute_import 希望有个更详细的讲解. A: 相对导入:在不指明 package ...
- from __future__ import unicode_literals
为了适应Python 3.x的新的字符串的表示方法,在2.7版本的代码中,可以通过unicode_literals来使用Python 3.x的新的语法
- from __future__ import division
导入python未来支持的语言特征division(精确除法),当我们没有在程序中导入该特征时,"/"操作符执行的是截断除法(Truncating Division),当我们导入精 ...
- python from __future__ import division
1.在python2 中导入未来的支持的语言特征中division(精确除法),即from __future__ import division ,当我们在程序中没有导入该特征时,"/&qu ...
- from __future__ import包的作用
__future__是python2的概念,其实是为了使用python2时能够去调用一些在python3中实现的特性 1.absolute_import from __future__ import ...
- from __future__ import absolute_import
from __future__ import absolute_import 这样以后:局部的包将不能覆盖全局的包, 本地的包必须使用相对引用了. 例: from celery import Cele ...
- 【python】只执行普通除法:添加 from __future__ import division
from __future__ import division 注意future前后是两个下划线
随机推荐
- 迁移到阿里云后,NTKO控件报存word 报文件存取错误,请检查网络传输。
解决办法:安装如下组件即可!
- [置顶]
kubernetes1.8发布跟踪
一.Kubernetes发布历史回顾 1. Kubernetes 1.0 - 2015年7月发布 2. Kubernetes 1.1 - 2015年11月发布 3. ...
- Recorder︱深度学习小数据集表现、优化(Active Learning)、标注集网络获取
一.深度学习在小数据集的表现 深度学习在小数据集情况下获得好效果,可以从两个角度去解决: 1.降低偏差,图像平移等操作 2.降低方差,dropout.随机梯度下降 先来看看深度学习在小数据集上表现的具 ...
- 机器学习算法实现解析——libFM之libFM的训练过程之Adaptive Regularization
本节主要介绍的是libFM源码分析的第五部分之二--libFM的训练过程之Adaptive Regularization的方法. 5.3.Adaptive Regularization的训练方法 5. ...
- python函数作用域
python中函数作用域 在python中,一个函数就是一个作用域 name = 'xiaoyafei' def change_name(): name = '肖亚飞' print('在change_ ...
- linux uname和dpkg命令
uname -a:查看系统一些参数 dpkg -i:安装下载好的.deb包裹
- 【javascript】js处理字符串
javascript常用方法锦集: 处理字符串 在Javascript除了使用数组和对象 String.replace(regexp | replaceThis,replaceWith |callba ...
- 如何写一个LaTeX类文件,并设计你自己的简历
2017/8/29 20:26:03 原文地址 https://www.sharelatex.com/blog/2011/03/27/how-to-write-a-latex-class-file-a ...
- 像黑客一样!Chrome 完全键盘操作指南(原生快捷键 + Vimium 插件)
有那么一波小伙伴,多数时候都不需要用到鼠标,通常他们正好是“黑客”.当你开始使用键盘操作一切时,便能体会到无需用鼠标瞄准按钮时的干脆,无需在键盘和鼠标之间移动手时的轻松. Chrome 原生自带大量快 ...
- LOJ #3049. 「十二省联考 2019」字符串问题
LOJ #3049. 「十二省联考 2019」字符串问题 https://loj.ac/problem/3049 题意:给你\(na\)个\(A\)类串,\(nb\)个\(B\)类串,\(m\)组支配 ...