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:

  • strict - The default value of errors. It raises an exception named UnicodeDecodeError, on failure
  • ignore - This value to errors is used to ignore the unencodable Unicode
  • replace - This value is used to replace the unencodable Unicode to a question mark (?)
  • xmlcharrefreplace - This value is used to insert an XML character reference, instead of unencodable Unicode
  • backslashreplace - This value is used to insert an escape sequence \uNNNN, instead of unencodable Unicode
  • namereplace - This value is also used to insert an escape sequence \N{...}, instead of unencodable Unicode

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 »