原文链接:

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

参考资料:

 
 

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

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

    add by zhj: 在Python中有些库的接口要求参数必须是str类型字符串,有些接口要求参数必须是unicode类型字符串.对于str类型的字符串,调用len()和遍历时,其实都是以字节为单位 ...

  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. vue.js 源代码学习笔记 ----- instance proxy

    /* not type checking this file because flow doesn't play well with Proxy */ import config from 'core ...

  2. mysql连接踩坑

    本机安装的是wamp,集成了mysql.php.apache.安装了sqlyog客户端. 1.错误代码2003 证明mysql服务没有开启,此时需要开启mysql服务,开启了wamp 2.错误代码10 ...

  3. 深度学习(六十七)metal forge深度学习库使用

    1.设置输入: let input = Input() 或者 let input = Input(width: 100, height: 100, channels: 3) 2.创建网络: let o ...

  4. postgresql与Oracle:空字符串与null

    空字符串:两个单引号,中间无空格等任何内容 在postgresql中,空字符串与null是不同的:而oracle中,空字符串与null等同.测试如下: postgresql中: postgres=# ...

  5. 单机ZooKeeper配置

    1.创建zoo.cfg copy D:\zookeeper3.4.6\conf\zoo_sample.cfg zoo.cfg 修改追加如下内容 dataDir=D:/zookeeper3.4.6/da ...

  6. 删除rz上传失败乱码的文件

    [摘要:经过rz上传文件失利时,会发生巨细为0的治码的文件,以下 ls-l -rw-rr1rootroot4703112-1513:48???.htm 这类范例的文件可用以下敕令 find.-maxd ...

  7. erl_0016 《硝烟中的erlang》 读书笔记003 “error_logger 爆炸”

    error_logger 爆炸 具有讽刺意味的是,负责错误日志的进程竟然是最为脆弱的之一.在Erlang的缺省安装中,error_logger39负责记录日志(写入磁盘或者发送到网络上),它的速度要比 ...

  8. bzoj 5288 游戏

    bzoj 5288 游戏 显然从点 \(x\) 出发,能到达的点是包含 \(x\) 的一段区间.用 \(L,R\) 两个数组记录每个点对应的区间端点. 如果能预处理出 \(L,R\) ,询问显然可以 ...

  9. BZOJ2431 HAOI2009 逆序对数列 【DP】*

    BZOJ2431 HAOI2009 逆序对数列 Description 对于一个数列ai{a_i}ai​,如果有i<j且ai>aja_i>a_jai​>aj​,那么我们称aia ...

  10. BZOJ4033 HAOI2015 树上染色 【树上背包】

    BZOJ4033 HAOI2015 树上染色 Description 有一棵点数为N的树,树边有边权.给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑色,并将其他的N-K个点染成白 ...