一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python中的编码问题解决方法

时间:2014-03-20 编辑:简简单单 来源:一聚教程网

在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
2. 引入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
      print now.strftime('%m月%d日 %H:%M')
UnicodeEncodeError: 'ascii' codec can't encode character u'u6708' in position 2: ordinal not in range(128)

3. 解决方案一:设置运行时编码为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')

正常执行

4. 解决方案二: 使用byte string

 代码如下 复制代码

#coding:utf-8
from __future__ import unicode_literals
from datetime import datetime

now = datetime.now()
print now.strftime(b'%m月%d日 %H:%M')  # 指明为bytearray字符串

# 或者这样也行
t = bytearray('%m月 %d %H:%M', 'utf-8')
print now.strftime(str(t))

热门栏目