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

notes d'expérience

outils en ligne

Fonctions en Python

Types de données en Python

tutoriel de base Python

O

objets et classes Python

date et heure Python

connaissances avancées Python

manuel de référence Python

Python built-in functions

utilisation et exemples de la méthode str() en Python

la fonction str() retourne la représentation en chaîne de caractères de l'objet donné.

la syntaxe de str() est :-8', errors='strict')

paramètres de str()

la méthode str() a trois paramètres :

  • objet- l'objet doit retourner sa représentation en chaîne de caractères. Si non fourni, retourne une chaîne de caractères vide

  • encoding-l'encodage de l'objet donné. Par défaut, si non fourniUTF-8.

  • errors-réponse lors de l'échec de la décodage. Par défaut, 'strict'.

il y a six types d'erreurs :

  • strict-réponse par défaut, lève une exception UnicodeDecodeError en cas d'échec

  • ignore -ignorer les Unicode non encodables dans le résultat

  • replace -remplacer les Unicode non encodables par un point d'interrogation

  • xmlcharrefreplace -insérer des caractères de référence XML plutôt que des Unicode non encodables

  • backslashreplace-Insert the \uNNNNspace sequence instead of unencodable Unicode

  • namereplace-Insert the \N{...} escape sequence instead of unencodable Unicode

str() return value

The str() method returns a string that is considered the informal or printable representation of the given object.

Example1: Convert to string

If not providedencodinganderrorsIf the parameters are not provided, the __str__() method of the object is called internally in str().

If the __str__() method is not found, it callsrepr(obj).

result = str(10)
print(result)

Output result

10

Note:The result variable will contain a string.

You can also try these commands on the Python command line.

>>> str('Adam')
>>> str(b'Python!')

Example2How does str() handle bytes?

If the encoding and errors parameters are provided, the first parameter object should be an object similar to bytes (bytesorbytearray)

If the object is bytes or bytearray, the bytes.decode(encoding, errors) is called internally in str().

Otherwise, it will get the bytes object in the buffer before calling the decode() method.

# bytes
b = bytes('pythön', encoding='utf-8)
print(str(b, encoding='ascii', errors='ignore'))

Output result

pythn

Here, the character 'ö' cannot be decoded through ASCII. Therefore, it should raise an error. However, we have set errors='ignore'. Therefore, the Python str() function will ignore characters that cannot be decoded.

Python built-in functions