python中文乱码的解决方法

yipeiwu_com5年前Python基础

乱码原因:

源码文件的编码格式为utf-8,但是window的本地默认编码是gbk,所以在控制台直接打印utf-8的字符串当然是乱码了!

解决方法:

1、print mystr.decode('utf-8').encode('gbk')
2、比较通用的方法:

import sys
type = sys.getfilesystemencoding()
print mystr.decode('utf-8').encode(type)

1. Python中列表或字典输出乱码的解决方法

问题: Python中的列表(list)或字典包含中文字符串,直接使用print会出现以下的结果:

#打印字典
dict = {'name': '张三'}
print dict
>>>{'name': '\xe5\xbc\xa0\xe4\xb8\x89'}

#打印列表
list = [{'name': '张三'}]
print list
>>>[{'name': '\xe5\xbc\xa0\xe4\xb8\x89'}]

解决方案:
使用以下方法进行输出:

import json

#打印字典
dict = {'name': '张三'}
print json.dumps(dict, encoding="UTF-8", ensure_ascii=False)
>>>{'name': '张三'}

#打印列表
list = [{'name': '张三'}]
print json.dumps(list, encoding="UTF-8", ensure_ascii=False)
>>>[{'name': '张三'}]

2. Python2.7的UnicodeEncodeError: ‘ascii' codec can't encode异常错误

#重置编码格式
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

以上就是python中文乱码的解决方法的详细内容,更多关于python乱码的资料请关注【听图阁-专注于Python设计】其它相关文章!

相关文章

python正则表达式match和search用法实例

本文实例讲述了python正则表达式match和search用法。分享给大家供大家参考。具体分析如下: python提供了2中主要的正则表达式操作:re.match 和 re.searc...

python 批量添加的button 使用同一点击事件的方法

python 批量添加的button 使用同一点击事件根据传递的参数进行区分。 def clear_text(): print '我只是个清空而已' def clear_tex...

解决Tensorflow使用pip安装后没有model目录的问题

解决Tensorflow使用pip安装后没有model目录的问题

在使用pip安装Tensorflow后,在其目录中没有找到model目录,重复安装了两遍依然没有,原因未知。 于是,使用源码安装的方法: (1)收下,使用git clone源码工程: g...

python进程的状态、创建及使用方法详解

本文实例讲述了python进程的状态、创建及使用方法。分享给大家供大家参考,具体如下: 进程以及状态 1. 进程 程序:例如xxx.py这是程序,是一个静态的 进程:一个程序运行起来后,...

python连接、操作mongodb数据库的方法实例详解

本文实例讲述了python连接、操作mongodb数据库的方法。分享给大家供大家参考,具体如下: 数据库连接 from pymongo import MongoClient imp...