Python str()

The str() method returns the "informal" or nicely printable representation of a given object.

The syntaxes of str() are:

str(object='')
str(object=b'', encoding='utf-8', errors='strict')

str() Parameters

The str() method mainly takes three parameters which are same for both constructs:

  • object - object whose informal representation is to be returned
  • encoding - Defaults of UTF-8. Encoding of the given object
  • errors - response when decoding fails. There are six types of error response
    • strict - default response which raises a UnicodeDecodeError exception on failure
    • ignore - ignores the unencodable unicode from the result
    • replace - replaces the unencodable unicode to a question mark ?
    • xmlcharrefreplace - inserts XML character reference instead of unencodable unicode
    • backslashreplace - inserts a \uNNNN espace sequence instead of unencodable unicode
    • namereplace - inserts a \N{...} escape sequence instead of unencodable unicode

Return value from str()

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


Example 1: How str() works in Python?

If encoding and errors parameter isn't provided, str() method internally calls __str__() method of an object.

If it cannot find the __str__() method, it instead calls repr(obj).

str('10')

When you run the program, the output will be:

'10'

Note: Notice the single quotes to represent the string.

Try str('Adam') or str(b'Python!') on the Python console.


Example 2: How str() works for bytes?

If encoding and errors parameter is provided, the first parameter (object) should be a bytes-like-object (bytes or bytearray).

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

Otherwise, it gets 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'))

When you run the program, the output will be:

pythn

Since, the character 'ö' cannot be decoded by ASCII, it gives out an error.

But, since we set the errors='ignore', it ignores the character which cannot be decoded by str(), i.e. ö

This results in the output pythn.