Python Tutorial Python Advanced Python References Python Libraries

Python str() Function



The Python str() function returns the string version of the given object. This function has two optional parameters: encoding and errors. Please note that, encoding and errors, if present, must be given as keyword arguments.

If encoding and errors parameters are not provided, str() function calls __str()__ function internally. If __str()__ function is not found, it calls repr(object).

Syntax

str(object, encoding, errors)

Parameters

object Required. Specify the object to convert into string. If nothing is specified, returns empty string.
encoding Optional. Specify encoding of the literal. Default: UTF-8.
errors Optional. Specify response when encoding fails. Default: 'strict'. There are six types of errors:
  • strict : Default response, raises an error on failure.
  • ignore : Ignores the unencodable characters.
  • replace : Replaces the unencodable character with a question mark.
  • xmlcharrefreplace : Replaces the unencodable character with an xml character.
  • backslashreplace : Replaces unencodable characters with a \uNNNN escape sequence.
  • namereplace: Replaces unencodable characters with a \N{...} escape sequence.

Example: using str() function

In the example below, str() function is used to get the string version of the given object.

MyList = [10, 20, 30]
print(str(MyList))

The output of the above code will be:

[10, 20, 30]

Example: using str() function with bytes

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

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

The output of the above code will be:

pythn
pyth��n

❮ Python Built-in Functions

5