使用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时要注意的问题
原文链接: http://www.cnblogs.com/ajianbeyourself/p/4471035.html 使用from __future__ import unicode_literal ...
- 转 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前后是两个下划线
随机推荐
- [Android]Volley源代码分析(叁)Network
假设各位看官细致看过我之前的文章,实际上Network这块的仅仅是点小功能的补充.我们来看下NetworkDispatcher的核心处理逻辑: <span style="font-si ...
- 【Objective-C】02-Objective-C学习及iOS开发的准备
前言 由于大部分朋友对iOS开发还是有比较多的疑问,比如是不是一定要买iPhone和苹果笔记本才能做iOS开发?因此,这讲就为广大有意学习iOS开发的朋友们进行解惑. 一.什么是iOS开发 iOS是由 ...
- 谈一谈APP版本号问题
如题:谈一谈APP版本号问题 为什么要谈这个问题,周五晚上11~12点,被微信点名,说APP有错,无效的版本号,商城无法下单.我正在准备收拾东西,周末回老家,结果看到这样问题,菊花一紧.我擦,我刚加的 ...
- c++的set_unexpected不起作用
代码是从:http://www.cplusplus.com/referen ... /?kw=set_unexpected找的 // set_unexpected example #include & ...
- Oracle Explain plan 使用总结
Oracle Explain plan使用总结 写多了SQL语句,伴随着数据量的海增,总会遇到性能的问题.在Oracle领域一个不好的习惯,一旦遇到性能问题就推给DBA来做.长期如此,反而对DB ...
- C++读取Sql Server
代码如下: // ReadSqlConsole.cpp: 主项目文件. #include "stdafx.h" #include <iostream> #include ...
- Ubuntu/Mac彻底解决手机ADB识别问题
之前写过一篇同样解决手机识别问题的文章(http://www.cnblogs.com/benhero/p/4202967.html) ,不过今天在遇到特殊手机"魅族"!之前的解决方 ...
- Servlet 容器对URI的处理
问题 请求到达server以后,server是怎样处理URI请求资源路径的,在与web.xml文件里的映射进行比对时的原则是什么. 方案 针对精确匹配.通配符匹配.后缀匹配三种模式改动web.xml文 ...
- BT下载原理分析
版权声明:本文为博主原创文章,未经博主允许不得转载. BitTorrent协议. BT全名为BitTorrent,是一个p2p软件,你在下载download的同时,也在为其他用户提供上传upload, ...
- java模板引擎替换代码
import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.re ...