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')

参考资料:

使用from __future__ import unicode_literals时要注意的问题的更多相关文章

  1. 转 - 使用from __future__ import unicode_literals时要注意的问题

    原文链接: http://www.cnblogs.com/ajianbeyourself/p/4471035.html 使用from __future__ import unicode_literal ...

  2. 转 from __future__ import unicode_literals

    转自 https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868200230 ...

  3. from __future__ import unicode_literals, absolute_import

    Q:python模块中的相对导入,绝对导入,有些地方会写 from __future__ import absolute_import 希望有个更详细的讲解. A: 相对导入:在不指明 package ...

  4. from __future__ import unicode_literals

    为了适应Python 3.x的新的字符串的表示方法,在2.7版本的代码中,可以通过unicode_literals来使用Python 3.x的新的语法

  5. from __future__ import division

    导入python未来支持的语言特征division(精确除法),当我们没有在程序中导入该特征时,"/"操作符执行的是截断除法(Truncating Division),当我们导入精 ...

  6. python from __future__ import division

    1.在python2 中导入未来的支持的语言特征中division(精确除法),即from __future__ import division ,当我们在程序中没有导入该特征时,"/&qu ...

  7. from __future__ import包的作用

    __future__是python2的概念,其实是为了使用python2时能够去调用一些在python3中实现的特性 1.absolute_import from __future__ import ...

  8. from __future__ import absolute_import

    from __future__ import absolute_import 这样以后:局部的包将不能覆盖全局的包, 本地的包必须使用相对引用了. 例: from celery import Cele ...

  9. 【python】只执行普通除法:添加 from __future__ import division

    from __future__ import division 注意future前后是两个下划线

随机推荐

  1. java使用lambda表达式对List集合进行操作(JDK1.8)

    1. 使用lambda表达式对List集合进行操作(JDK1.) List<TreeDto> collect = list.stream().filter(item -> item. ...

  2. 221. Add Two Numbers II【medium】

    You have two numbers represented by a linked list, where each node contains a single digit. The digi ...

  3. poj 1182 食物链 并查集的又一个用法

    食物链   Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 41584   Accepted: 12090 Descripti ...

  4. hdoj 1288 Hat's Tea

    Hat's Tea Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total S ...

  5. iOS网络访问之使用AFNetworking

    AFNetworking是IOS上常用的第三方网络访问库,我们可以在github上下载它,同时github上有它详细的使用说明,最新的AFNetworing2.0与1.0有很大的变化,这里仅对2.0常 ...

  6. mahout相关介绍

    https://blog.csdn.net/xiaopihaierletian/article/details/72674592 https://www.cnblogs.com/zlslch/p/67 ...

  7. 'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set.

    UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATA ...

  8. 【转】Oracle Sys和system用户、sysdba 和sysoper系统权

    一:最重要的区别,存储的数据的重要性不同 [sys]所有oracle的数据字典的基表和视图都存放在sys用户中,这些基表和视图对于oracle的运行是至关重要的,由数据库自己维护,任何用户都不能手动更 ...

  9. php socket编程入门

    服务端 <?php /** * File name server.php * 服务器端代码 * * @author guisu.huang * @since 2012-04-11 * */ // ...

  10. C++ namespace浅析

    有一些C语言的基础,突然想看看C++,在Codeblocks上新建工程的时候会生成一个打印"Hello World"的程序,和C语言些许不同.其中最突出的就是"using ...