Python str()

The str() function returns the string version of the given object.

The syntax of str() is:

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

1. str() Parameters

The str()method takes three parameters:

  • object – The object whose string representation is to be returned. If not provided, returns the empty string
  • encoding – Encoding of the given object. Defaults of UTF-8 when not provided.
  • errors – Response when decoding fails. Defaults to 'strict'.

There are six types of errors:

  • 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

2. Return value from str()

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

3. Example 1: Convert to String

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

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

result = str(10)
print(result)

Output:

10

Note: The result variable will contain a string.

Also try these commands on the Python console.

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

4. 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 bytearraystr() 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'))

Output

pythn

Here, the character 'ö' cannot be decoded by ASCII. Hence, it should give an error. However, we have set the errors ='ignore'. Hence, Python ignores the character which cannot be decoded by str().