English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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')
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
The str() method returns a string that is considered the informal or printable representation of the given object.
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!')
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.