search
HomeBackend DevelopmentPython TutorialIn-depth analysis of Python coding
In-depth analysis of Python codingJul 18, 2017 pm 01:27 PM
pythonanalyze

It is said that everyone who develops Python is confused by character encoding problems. The most common errors are UnicodeEncodeError and UnicodeDecodeError. You seem to know how to solve them. Unfortunately, the errors appear in other places, and the problem is always Repeating the same mistake, it is very difficult to remember whether to use decode or encode method to convert str to unicode. I am always confused. Where is the problem?

In order to clarify this problem, I decided to conduct an in-depth analysis from the composition of python strings and the details of character encoding

Bytes and characters

Everything stored in the computer Data, text characters, pictures, videos, audios, and software are all composed of a sequence of 01 bytes. One byte is equal to 8 bits.

A character is a symbol. For example, a Chinese character, an English letter, a number, and a punctuation mark can all be called a character.

Bytes are convenient for storage and network transmission, while characters are used for display and easy to read. For example, the character "p" stored on the hard disk is a string of binary data 01110000, which occupies one byte in length

Encoding and decoding

The text we open with the editor, Every character you see is stored in the form of a binary byte sequence when it is finally saved on the disk. Then the conversion process from characters to bytes is called encoding, and the reverse is called decoding. The two are reversible processes. Encoding is for storage and transmission, and decoding is for display and reading.

For example, the character "p" is encoded and saved to the hard disk as a sequence of binary bytes 01110000, occupying one byte in length. The character "Zen" may be stored as "11100111 10100110 10000101" occupying a length of 3 bytes. Why is it possible? We’ll talk about this later.

Why is Python coding so painful? Of course, this cannot be blamed on the developers.

This is because Python2 uses ASCII character encoding as the default encoding, and ASCII cannot handle Chinese, so why not use UTf-8? Because Dad Guido wrote the first line of code for Python in the winter of 1989, and the first version was officially open sourced and released in February 1991, and Unicode was released in October 1991, which means that the language Python was created. UTF-8 hadn't been born yet, so this was one of them.

Python also divides the string types into two types, unicode and str, so that developers are confused. This is the second reason. Python3 has completely reshaped strings, retaining only one type. This is a story for later.

str and unicode

Python2 divides strings into two types: unicode and str. In essence, str is a sequence of binary bytes. As can be seen from the example code below, the "Zen" of str type is printed as hexadecimal \xec\xf8, and the corresponding binary byte sequence is '11101100 11111000'.

>>> s = '禅'
>>> s
'\xec\xf8'
>>> type(s)
<type &#39;str&#39;>

The corresponding unicode symbol of the unicode type u"Zen" is u'\u7985′

>>> u = u"禅"
>>> u
u&#39;\u7985&#39;
>>> type(u)
<type &#39;unicode&#39;>

If we want to save the unicode symbol to a file or transmit it to the network, we need to go through encoding processing and conversion into str type, so python provides the encode method to convert from unicode to str and vice versa.

##encode

>>> u = u"禅"
>>> u
u&#39;\u7985&#39;
>>> u.encode("utf-8")
&#39;\xe7\xa6\x85&#39;

decode

>>> s = "禅"
>>> s.decode("utf-8")
u&#39;\u7985&#39;
>>>

Many beginners cannot remember whether to use encode or unicode to convert between str and unicode decode, if you remember that str is essentially a string of binary data, and unicode is a character (symbol), encoding is the process of converting characters (symbols) into binary data, so the conversion from unicode to str needs to be The encode method, in turn, uses the decode method.

encoding always takes a Unicode string and returns a bytes sequence, and decoding always takes a bytes sequence and returns a Unicode string”.

After clarifying the conversion relationship between str and unicode, let’s take a look at when UnicodeEncodeError and UnicodeDecodeError errors will occur.


UnicodeEncodeError

UnicodeEncodeError occurs when a unicode string is converted into a str byte sequence. Let's look at an example of saving a string of unicode strings to a file

# -*- coding:utf-8 -*-
def main():
    name = u&#39;Python之禅&#39;
    f = open("output.txt", "w")
    f.write(name)

Error log

UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 6-7: ordinal not in range(128)

Why does UnicodeEncodeError occur?


Because when calling the write method, Python will first determine what type the string is. If it is str, it will be written directly to the file without encoding, because the str type string itself is a string of binary byte sequence.

If the string is of unicode type, it will first call the encode method to convert the unicode string into the binary str type before saving it to the file, and the encode method will use python's default ascii code to encode

Equivalent to:

>>> u"Python之禅".encode("ascii")

However, we know that the ASCII character set only contains 128 Latin letters, excluding Chinese characters, so the 'ascii' codec can't encode characters error occurs. To use encode correctly, you must specify a character set that contains Chinese characters, such as UTF-8, GBK.

>>> u"Python之禅".encode("utf-8")
&#39;Python\xe4\xb9\x8b\xe7\xa6\x85&#39;

>>> u"Python之禅".encode("gbk")
&#39;Python\xd6\xae\xec\xf8&#39;

So to write unicode strings to files correctly, you should convert the strings to UTF-8 or GBK encoding in advance.

def main():
    name = u&#39;Python之禅&#39;
    name = name.encode(&#39;utf-8&#39;)
    with open("output.txt", "w") as f:
        f.write(name)

当然,把 unicode 字符串正确地写入文件不止一种方式,但原理是一样的,这里不再介绍,把字符串写入数据库,传输到网络都是同样的原理

UnicodeDecodeError

UnicodeDecodeError 发生在 str 类型的字节序列解码成 unicode 类型的字符串时

>>> a = u"禅"
>>> a
u&#39;\u7985&#39;
>>> b = a.encode("utf-8")
>>> b
&#39;\xe7\xa6\x85&#39;
>>> b.decode("gbk")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: &#39;gbk&#39; codec can&#39;t decode byte 0x85 in position 2: incomplete multibyte sequence

把一个经过 UTF-8 编码后生成的字节序列 ‘\xe7\xa6\x85′ 再用 GBK 解码转换成 unicode 字符串时,出现 UnicodeDecodeError,因为 (对于中文字符)GBK 编码只占用两个字节,而 UTF-8 占用3个字节,用 GBK 转换时,还多出一个字节,因此它没法解析。避免 UnicodeDecodeError 的关键是保持 编码和解码时用的编码类型一致。

这也回答了文章开头说的字符 “禅”,保存到文件中有可能占3个字节,有可能占2个字节,具体处决于 encode 的时候指定的编码格式是什么。

再举一个 UnicodeDecodeError 的例子

>>> x = u"Python"
>>> y = "之禅"
>>> x + y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: &#39;ascii&#39; codec can&#39;t decode byte 0xe4 in position 0: ordinal not in range(128)
>>>

str 与 unicode 字符串 执行 + 操作是,Python 会把 str 类型的字节序列隐式地转换成(解码)成 和 x 一样的 unicode 类型,但Python是使用默认的 ascii 编码来转换的,而 ASCII 中不包含中文,所以报错了。

>>> y.decode(&#39;ascii&#39;)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: &#39;ascii&#39; codec can&#39;t decode byte 0xe4 in position 0: ordinal not in range(128)

正确地方式应该是显示地把 y 用 UTF-8 或者 GBK 进行解码。

>>> x = u"Python"
>>> y = "之禅"
>>> y = y.decode("utf-8")
>>> x + y
u&#39;Python\u4e4b\u7985&#39;

以上内容都是基于 Python2 来讲的,关于 Python3 的字符和编码将会另开一篇文章来写,保持关注。

The above is the detailed content of In-depth analysis of Python coding. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment