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

Notas de experiência

Ferramentas online

Função do Python

Tipos de Dados do Python

Tutorial básico do Python

O

Objetos e classes do Python

Data e hora do Python

Conhecimento avançado do Python

Manual de referência do Python

Python built-in functions

Uso e exemplo do str() em Python

o str() retorna a representação de string do objeto fornecido.

a sintaxe do str() é:-8', errors='strict')

parâmetros do str()

o método str() possui três parâmetros:

  • objeto- objeto para retornar sua representação de string. Se não fornecido, retorna uma string vazia

  • encoding-codificação do objeto fornecido. O valor padrão éUTF-8.

  • errors-resposta ao falhar na decodificação. O padrão é 'strict'.

existem seis tipos de erros:

  • strict-resposta padrão, levanta a exceção UnicodeDecodeError em caso de falha

  • ignore -ignorar Unicode não codificáveis no resultado

  • replace -substituir Unicode não codificáveis por um ponto de interrogação

  • xmlcharrefreplace -inserir caracteres de referência XML em vez de Unicode não codificáveis

  • backslashreplace-Insert \uNNNN space sequence instead of unencodable Unicode

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

str() return value

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

Example1: Convert to string

If not providedencodinganderrorsIf the parameter is not provided, the method of the __str__() 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 specified platform.

>>> 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, then 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 give an error. However, we have set errors = 'ignore'. Therefore, the Python str() function will ignore characters that cannot be decoded.

Python built-in functions