python2.x default encoding problem solution
pythonProcessing Chinese in 2.x is a headache. Articles written in this area on the Internet have been unevenly tested, and there are always mistakes, so I plan to summarize an article myself.
I will also continue to modify this blog in the future study.
It is assumed that readers already have basic knowledge related to encoding. This article will not introduce it again, including what is utf-8, what is unicode, and what is the relationship between them.
str and bytecode
First of all, let’s not talk about unicode at all.
s = "人生苦短"
s is a string, which itself stores bytecode. So what is the format of this bytecode?
If this code is entered on the interpreter, then the format of this s is the encoding format of the interpreter. For Windows cmd, it is gbk.
If the code is saved and then executed, for example, stored as utf-8, then when the interpreter loads this program, s will be initialized to utf-8 encoding.
unicode and str
We know that unicode is an encoding standard, and the specific implementation standard may be utf-8, utf-16, gbk...
Python uses two bytes internally to store a unicode. The advantage of using unicode objects instead of str is that unicode is convenient for cross-platform.
You can define a unicode in the following two ways:
s1 = u"人生苦短" s2 = unicode("人生苦短", "utf-8")
encode and decode
The encoding and decoding in python is like this:
So we can write code like this:
# -*- coding:utf-8 -*- su = "人生苦短" # : su是一个utf-8格式的字节串 u = s.decode("utf-8") # : s被解码为unicode对象,赋给u sg = u.encode("gbk") # : u被编码为gbk格式的字节串,赋给sg print sg # 打印sg
But the reality is more complicated than this. For example, look at the following code:
s = "人生苦短" s.encode('gbk')
Why is this possible? Looking at the arrows of the encoding process in the picture above, you can think of the principle. When encoding str, it will first decode itself into unicode using the default encoding, and then encode unicode to the encoding you specify.
This leads to the reason why most errors occur when processing Chinese in python2.x: the default encoding of python, defaultencoding is ascii
Look at this example:
# -*- coding: utf-8 -*- s = "人生苦短" s.encode('gbk')
The above code will report an error, Error message: UnicodeDecodeError: 'ascii' codec can't decode byte...
Because you did not specify defaultencoding, so it Actually doing something like this:
# -*- coding: utf-8 -*- s = "人生苦短" s.decode('ascii').encode('gbk')
Set defaultencoding
The code to set defaultencoding is as follows:
reload(sys) sys.setdefaultencoding('utf-8')
For example, in the example in the previous section, if str is encoded into another format, defaultencoding will be used.
s.encode("utf-8") 等价于 s.decode(defaultencoding).encode("utf-8")
For another example, when you use str to create a unicode object, if you do not specify the encoding format of this str, the program will also use defaultencoding.
u = unicode("人生苦短") 等价于 u = unicode("人生苦短",defaultencoding)
The default defaultcoding: ascii is the cause of many errors, so setting the defaultencoding early is a good habit.
The file header declares the role of encoding.
Thanks to this blog for explaining the knowledge about the header part of python files.
The top:# -*- coding: utf-8 -*- currently seems to have three functions.
If there are Chinese comments in the code, this statement is needed
A more advanced editor (such as my emacs) will declare based on the header, Use this as the format for your code files.
The program will decode and initialize u "Life is short" through the header declaration, such a unicode object (so the storage format of the header declaration and the code must be consistent)
About requests library
requests is a very practical Python HTTP client library, which is often used when writing crawlers and testing server response data.
The Request object will return a Response object after accessing the server. This object saves the returned Http response bytecode into the content attribute.
But if you access another attribute text, a unicode object will be returned, and garbled characters will often occur here.
Because the Response object will encode the bytecode into unicode through another attribute encoding, and this encoding attribute is actually guessed by the responses themselves.
官方文档:
text
Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using chardet.
The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.
所以要么你直接使用content(字节码),要么记得把encoding设置正确,比如我获取了一段gbk编码的网页,就需要以下方法才能得到正确的unicode。
import requests url = "http://xxx.xxx.xxx" response = requests.get(url) response.encoding = 'gbk' print response.text
如果是早期的我写博客,那么我一定会写这样的例子:不仅仅要原理,更要使用方法!
如果现在的文件编码为gbk,然后文件头为:# -*- coding: utf-8 -*-,再将默认编码设置为xxx,那么如下程序的结果会是……
这就类似于,当年学c的时候,用各种优先级,结合性,指针来展示自己水平的代码。
实际上这些根本就不实用,谁会在真正的工作中写这样的代码呢?我在这里想谈谈实用的处理中文的python方法。
基本设置
主动设置defaultencoding。(默认的是ascii)
代码文件的保存格式要与文件头部的# coding:xxx一致
如果是中文,程序内部尽量使用unicode,而不用str
关于打印
你在打印str的时候,实际就是直接将字节流发送给shell。如果你的字节流编码格式与shell的编码格式不相同,就会乱码。
而你在打印unicode的时候,系统自动将其编码为shell的编码格式,是不会出现乱码的。
程序内外要统一
如果说程序内部要保证只用unicode,那么在从外部读如字节流的时候,一定要将这些字节流转化为unicode,在后面的代码中去处理unicode,而不是str。
with open("test") as f: for i in f: # 将读入的utf-8字节流进行解码 u = i.decode('utf-8') ....
如果把连接程序内外的这段数据流比喻成通道的的话,那么与其将通道开为字节流,读入后进行解码,不如直接将通道开为unicode的。
# 使用codecs直接开unicode通道 file = codecs.open("test", "r", "utf-8") for i in file: print type(i) # i的类型是unicode的
python 3和2很大区别就是python本身改为默认用unicode编码。
字符串不再区分"abc"和u"abc", 字符串"abc"默认就是unicode,不再代表本地编码、
由于有这种内部编码,像c#和java类似,再没有必要在语言环境内做类似设置编码,比如“sys.setdefaultencoding”;
也因此也python 3的代码和包管理上打破了和2.x的兼容。2.x的扩展包要适应这种情况改写。
另一个问题是语言环境内只有unicode怎么输出gbk之类的本地编码。
1.如果你在Python中进行编码和解码的时候,不指定编码方式,那么python就会使用defaultencoding。 而python2.x的的defaultencoding是ascii,
这也就是大多数python编码报错:“UnicodeDecodeError: 'ascii' codec can't decode byte ......”的原因。
2.关于头部的# coding:utf-8,有以下几个作用 2.1如果代码中有中文注释,就需要此声明 2.2比较高级的编辑器(比如我的emacs),会根据头部声明,将此作为代码文件的格式。 2.3程序会通过头部声明,解码初始化 u"人生苦短",这样的unicode对象,(所以头部声明和代码的存储格式要一致)
python2.7以后不用setdefaultencoding了,这两个是没有区别的
这两个作用不一样, 1. # coding:utf-8
作用是定义源代码的编码. 如果没有定义, 此源码中是不可以包含中文字符串的. PEP 0263 -- Defining Python Source Code Encodings https://www.python.org/dev/peps/pep-0263/ 2. sys.getdefaultencoding()
是设置默认的string的编码格式
答按惯例都在(序列化)输出时才转换成本地编码。
The above is the detailed content of python2.x default encoding problem solution. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.
