Python str() Function

The str() function in Python is used when we need to convert a value to a string object. For example:

a = 1234
x = str(a)
print(type(x))

a = 2.43
x = str(a)
print(type(x))

a = [12, 32, 43]
x = str(a)
print(type(x))

The output is:

<class 'str'>
<class 'str'>
<class 'str'>

Python str() Function Syntax

The syntax of str() function in Python, is:

str(object, encoding, errors)

where object refers to an object that is going to convert into a str object. The encoding parameter is used to apply the particular encoding method, while converting the object into string. And the errors parameter is used to specify what to do, in case, if decoding fails.

Note: The encoding and errors parameters are optional.

Note: The default value of encoding is UTF-8. And the default value of errors is strict.

Important - If encoding parameter is used to specify the encoding method, then the object must be a bytes object.

The errors parameter's value can be any of the following:

Python str() Function Example

Here is an example of str() function in Python:

a = 12
x = str(a)
print(x)

a = b'Python Programming'
x = str(a, 'ascii')
print(x)

a = b'Python Programming'
x = str(a, 'U7', 'replace')
print(x)

a = [12, 23, 43]
x = str(a)
print(x)
print(x[0])
print(x[1])
print(x[2])
print(x[3])
print(x[-1])

The snapshot given below shows the sample output produced by above program, demonstrating the str() function in Python:

python str function

Python Online Test


« Previous Function Next Function »