English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation et exemple de la chaîne encode() Python

Python string methods

La méthode encode() de la chaîne Python utilise l'encodage spécifié pour encoder la chaîne. Si l'encodage n'est pas spécifié, l'UTF sera utilisé-8.

à partir de Python 3depuis 0,Chaînestockée au format Unicode, c'est-à-direChaîneChaque caractère est représenté par un code point. Par conséquent, chaque chaîne est une séquence de code points Unicode.

Pour stocker efficacement ces chaînes, convertissez la séquence de code points en un ensemble de bytes. Ce processus s'appelleEncoding.

Il existe diverses encodings différentes, qui traitent les chaînes de manière différente. Les encodings populaires sontutf-8,asciietc.

En utilisant la méthode encode() de la chaîne, vous pouvez convertir une chaîne non codée en n'importe quel encodage pris en charge par Python. Par défaut, Python utiliseutf-8编码。

La syntaxe de la méthode encode() est :

string.encode(encoding='UTF-8',errors='strict')

Paramètre de la méthode encode() de la chaîne

Par défaut, la méthode encode() n'a besoin d'aucun paramètre.

Il renvoie une chaîne UTF-8Encoding version. If an error occurs, it will raise a UnicodeDecodeError exception.

But it needs two parameters:

  • encoding -The encoding type must be encoded as a string

  • errors-Response when encoding fails. There are six types of error responses

    • strict-Default response, which raises a UnicodeDecodeError exception when it fails

    • ignore-Ignore unencodable unicode from the result

    • replace-Replace unencodable Unicode with question mark?

    • xmlcharrefreplace-Insert XML character references instead of unencodable unicode

    • Backslash replacement-Insert \ uNNNN space sequences instead of unencodable unicode

    • namereplace-Insert \ N {...} escape sequences instead of unencodable unicode

Example1: Encoding is the default Utf-8Encoding

# Unicode string
string = 'pythön!'
# Output string
print('String:', string)
# Default encoding is utf-8
string_utf = string.encode()
# Output result
print('Encoding version is:', string_utf)

When running the program, the output is:

String: pythön!
Encoding version is: b'pyth\xc3\xb6n!"

Example2Use incorrect encoding parameters

# Unicode string
string = 'pythön!'
# Output string
print('String:', string)
# Ignore error
print('Encoded version (ignore) :', string.encode("ascii", "ignore"))
# Replace error
print('Encoded version (replace) :', string.encode("ascii", "replace"))

When running the program, the output is:

String: pythön!
Encoded version (ignore) : b'pythn!'
Encoded version (replace) : b'pyth?n!'

Note:Try different encoding and error parameters.

Python string methods