转 - 使用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前后是两个下划线
随机推荐
- JWT的详细简介
什么是JWT Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准.该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场 ...
- IIS站点/虚拟目录中访问共享目录(UNC)以及建立后的应用程序的信任级别问题
UNC是 Universal Naming Convention 的简称,也叫通用命名规范.通用命名约定.网络(范指局域网)上资源的完整位置名称.格式为 \\servername\sharenam ...
- UART介绍
https://baike.baidu.com/item/UART/4429746?fr=aladdin
- IOS开发 多线程编程 - NSOperation
一.NSOperation 1.简介 NSOperation实例封装了需要执行的操作和执行操作所需的数据,并且能够以并发或非并发的方式执行这个操作. NSOperation本身是抽象基类,因此必须使用 ...
- IOS开发 Application Kit框架的线程安全
以下部分介绍了Application Kit框架的线程安全. 非线程安全类 以下这些类和函数通常是非线程安全的.大部分情况下,你可以在任何线程使用这些类,只要你在同一时间只有一个线程使用它们.查看这些 ...
- Ethernet、VLAN、QinQ
以太网帧格式: 各字段解释: DMAC:目的MAC地址,该字段确定帧的接收者. SMAC:源MAC地址,该字段标识发送帧的工作站. Type:上层协议类型(0x0800:IP;0x0808:ARP;0 ...
- learn Linux sed command
learn Linux sed command 一.参考文档: . sed命令详解 http://qifuguang.me/2015/09/21/sed%E5%91%BD%E4%BB%A4%E8%AF ...
- BZOJ2120 数颜色 【带修莫队】
BZOJ2120 数颜色 Description 墨墨购买了一套N支彩色画笔(其中有些颜色可能相同),摆成一排,你需要回答墨墨的提问.墨墨会像你发布如下指令: 1. Q L R代表询问你从第L支画笔到 ...
- PHP获取客户端的IP、地理信息、浏览器、本地真实IP
<?php header("Content-type:text/html;charset=utf-8"); // 作用获取客户端的ip.地理信息.浏览器.本地真实IP cla ...
- asciidoctor 安装试用
备注: asciidoctor 是asciidoc 的增强,使用简单,模板比较丰富,对于持续集成方面的开发也是一个不错的工具 1. 安装 a. 环境准备 MRI Ruby 1.8.7, 1. ...