(转)python(三):Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1

                                                                                                            <div class="tags-box space">

                                                                                                        <a class="tag-link" target="_blank" rel="noopener" href="https://blog.csdn.net/ackclinkz/article/category/7262020">
python </a>
<a class="tag-link" target="_blank" rel="noopener" href="https://blog.csdn.net/ackclinkz/article/category/7289316">
编码 </a>
</div>
</div>
<div class="operating">
</div>
</div>
</div>
</div>
<article class="baidu_pl">
<div id="article_content" class="article_content clearfix">
<div class="article-copyright">
<span class="creativecommons">
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">
</a> <div class="article-source-link2222">
原文链接:<a href="https://blog.csdn.net/AckClinkz/article/details/78538462">https://blog.csdn.net/AckClinkz/article/details/78538462</a>
</div>
</span>
</div>
<!--一个博主专栏付费入口--> <!--一个博主专栏付费入口结束-->
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-d284373521.css">
<div id="content_views" class="markdown_views">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
</svg>
<h1 id="环境"><a name="t0"></a>环境</h1>
>>> import sys
>>> print(sys.version)
'3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 12:22:00) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]'

问题描述

今天在使用python3的时候,报错信息

Traceback (most recent call last):
File "tmp.py", line 3, in <module>
print(a)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

报错代码可简化为

a = b'\xe5\x94\xb1\xe6\xad\x8c'
a = a.decode("utf-8")
print(a)

问题分析

本节介绍问题的分析过程,如果想看解决办法,可以直接看一下节。

网上解释

网上给出的解释:错误的使用decode和encode方法会出现这种异常。例如使用decode方法将Unicode字符串转化的时候:

s = u'中文'
s.decode('utf-8')
print s

但是将这个例子放到python3环境中,会报错

Traceback (most recent call last):
File "tmp_2.py", line 4, in <module>
s.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'

熟悉python历史的朋友会知道,为了解决编码问题,在python3中,所有的字符串都是使用Unicode编码,统一使用str类型来保存,而str类型没有decode方法,所以网上给出的方向并不适合我的问题。

字符编码

为了确定是否是字符编码的问题,我换了一台python3机器,测试了一下

>>>a = b'\xe5\x94\xb1\xe6\xad\x8c'
>>>a = a.decode("utf-8")
>>>print(a)
唱歌

完全没有问题,正常输出,排除字符编码和代码失误。

输出

既然字符编码、代码都没有错,那么问题肯定出在print上面。这时我开始关注错误信息中的ascii。因为在一般python3环境中,输出时会将Unicode转化为utf-8。为了解开这个疑惑,查看了输出编码

>>>import sys
>>>sys.stdout.encoding
'ANSI_X3.4-1968'

竟然是ANSI_X3.4-1968,所以任何中文都会报错。哈哈,终于定位问题啦。

解决方案

定位问题后,解决办法就很简单啦,有两种方法

运行python的时候加上PYTHONIOENCODING=utf-8,即

PYTHONIOENCODING=utf-8 python your_script.py
  • 重新定义标准输出

标准输出的定义如下

sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

打印日志的方法

sys.stdout.write("Your content....")

总结

通过分析这个问题,进一步加深了对python3的了解。另外,希望各位看官批评指正!!

    </div>
</div>
posted @
2019-11-19 09:37 
热咖啡与白猫 
阅读(...) 
评论(...) 
编辑 
收藏

(转) Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1的更多相关文章

  1. 【转】Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1

    转自:https://blog.csdn.net/AckClinkz/article/details/78538462 环境 >>> import sys >>> ...

  2. python爬虫中对含中文的url处理以 及 Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position

    在练习urllib操作中,遇到了url中含有中文字符的问题.比如http://dotamax.com/,看下源码的话,上方的搜索框的name=p,输入内容点击搜索以后,通过GET方法进行传递,比如我们 ...

  3. python输出字符串,UnicodeEncodeError: 'ascii' codec can't encode characters in position问题

    2017-06-28更新:换到python3.x中,编码问题减少了很多.这篇博文不适用于python3.x http://blog.sina.com.cn/s/blog_64a3795a01018vy ...

  4. Mac sublime 编译Python UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-8: ordinal not in range(128)

    刚学Python,想打印个“hello 张林峰”,代码如下: #!/usr/bin/env python3 # -*- coding: utf-8 -*- print('hello 张林峰') 用su ...

  5. Python编码问题:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(12

    今天安装了PyScripter编辑器,刚要写代码,突然就出现异常: <span style="font-size:14px;color:#ff0000;">>&g ...

  6. python+selenium运行报错UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

    使用python+selenium运行自动化脚本时,打印某一段文字出现UnicodeEncodeError: 'ascii' codec can't encode characters in posi ...

  7. Pip 安装 出现UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in

    在Python 环境下,使用PiP 命令安装时,报错提示: UnicodeEncodeError: 'ascii' codec can't encode characters in position ...

  8. 解决UnicodeEncodeError: 'ascii' codec can't encode characters in position 问题(转)

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-11: ordinal not in range(128 ...

  9. UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)

    python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报类似这样的错误. UnicodeEncodeError: 'ascii' codec can't ...

随机推荐

  1. Java NIO Buffer详解

    一.ByteBuffer类型化的put与get方法 /** * ByteBuffer类型化的put与get方法 */ public class NioTest5 { public static voi ...

  2. Mysql 查询今天,这周,这个月,今年的数据

    今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ...

  3. 使用ES6删除对象中某些属性

    const form = { id: '011', name: '测试一', description: '测试demo' } // 目标: 取到删除description属性的对象, 即下文的data ...

  4. 阻止Bootstrap 模态框点击背景空白处自动关闭

    问题描述 模态框点击空白处,会自动关闭,怎么阻止关闭事件呢? 解决方法 在HTML页面中编写模态框时,在div初始化时添加属性 aria-hidden=”true” data-backdrop=”st ...

  5. 闭包(python)

    1.闭包的理解 我们可以将闭包理解为一种特殊的函数,这种函数由两个函数的嵌套组成,且称之为外函数和内函数,外函数返回值是内函数的引用,此时就构成了闭包. 2. 闭包的格式 下面用伪代码进行闭包格式的描 ...

  6. 【转】Revit二次开发——读取cad中的文字信息

    Revit读取cad的文字信息需要借助Teigha的开源dll,在程序中添加下图中红色框的dll文件的引用,其他的dll文件全部放在同一个文件夹中即可,运行的时候,会自动把这些dll文件全部复制到bi ...

  7. IDEA光标类的操作

    1.Ctrl+Alt+Left/Right   光标定位到上一个/下一个浏览位置处: 2.Ctrl+Shift+Backspace   光标定位到上次修改的地方: 3.Alt+Up/Down   移动 ...

  8. Qt编写安防视频监控系统17-在线地图

    一.前言 在线地图模块在一开始设计整个系统的时候就考虑进去了,主要功能就是在摄像机管理中,提供经纬度信息,然后加载百度地图在浏览器中显示,根据摄像机信息表中的每个摄像机的经纬度信息,自动生成设备点在地 ...

  9. 爬虫相关-scrapy框架介绍

    性能相关-进程.线程.协程 在编写爬虫时,性能的消耗主要在IO请求中,当单进程单线程模式下请求URL时必然会引起等待,从而使得请求整体变慢. 串行执行 import requests def fetc ...

  10. EasyNVR摄像机网页无插件直播方案H5前端构建之:使用BootstrapPagination以分页形式展示数据信息

    背景介绍 EasyNVR核心在于摄像机的音视频流的获取.转换.转码与高性能分发,同时同步完成对实时直播流的录像存储,在客户端(PC浏览器.Android.iOS.微信)进行录像文件的检索.回放和下载. ...