Tutorial Study Image

Python str()

The built-in function str() is used to convert the given object into the string format. The behavior of the output string depends on the arguments encoding and errors.

str(object, encoding='utf-8', errors='strict') #where object is whoes string representation needed

str() Parameters:

Takes three parameters. The argument errors are of six types as below

strict - 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 - instead of unencodable Unicode inserts XML character reference

backslashreplace - instead of unencodable Unicode it inserts a \uNNNN espace sequence

namereplace - instead of unencodable Unicode it inserts a \N{...} escape sequence 

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

str() Return Value

This returns a string object which is in a printable format. If parameter encoding and errors are missing, the str()  function internally calls the __str__() method of an object.

Input Return Value
 If object string

Examples of str() method in Python

Example 1: How to convert using str()

output = str(25)



Example 2:How str() works for bytes?

# bytes
byt = bytes('pythön', encoding='utf-8')

print(str(byt, encoding='ascii', errors='ignore'))



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