The str() function is used to convert a specified object to a string type. If the object is already a string type, it returns the object itself; otherwise, it calls the object's __str__() method to perform the conversion.

Function Syntax

This function exists in two forms:

1. Single Argument Form

str(object='')

object can be any object. It will call the object's __str__() method for conversion.

If the object does not define a __str__() method, it will call that method from its parent class.

2. Multiple Arguments Form

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

object must be a bytes object. The function will decode it using the specified encoding method.

Examples of the str() Function

Applied to any type:

print(str(123))       # 123
print(str(3.14159))   # 3.14159
print(str(True))      # True
print(str([1,2,3,4])) # [1, 2, 3, 4]

class MyClass:
    def __str__(self):
        return 'MyClass'

my = MyClass()
print(my) # MyClass

Applied to bytes objects:

# UTF-8 encoding for '你好'
chinese_bytes = b'\xe4\xbd\xa0\xe5\xa5\xbd'

print(chinese_bytes)
print(str(chinese_bytes,encoding='utf-8'))
b'\xe4\xbd\xa0\xe5\xa5\xbd'
你好