Python str() Method

The str() constructor method returns an object of the str class with the specified value.

Syntax:

str(object, encoding, errors)

Parameters:

  1. object: (Optional) The int, float, boolean, or any other object whose value needs to be converted to a string.
  2. encoding: (Optional) Encoding of the specified object. Defaults is UTF-8.
  3. errors: (Optional) Response when decoding fails. Defaults to 'strict'

Return Value:

Returns a string.

The following example converts an integer to string.

Example: Integer to String
numstr = str(10)
print(numstr)
print(type(numstr))
Output
10
<class 'str'>

The following converts different values to string.

Example: Converts to String
fstr = str(10.5)
bstr = str(True)
cstr = str(3+4j)

print(fstr)
print(bstr)
print(cstr)
Output
'10.5'
'True'
'(3+4j)'

If encoding or errors is specified, then the object should be of bytes or bytesarray type. If the specified object is of bytes type, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Passing bytes without encoding would fail and simply return string.

Example:
print(str(b'Hello'))
Output
"b'hello'"

The following converts bytes to string.

Example:
b = bytes('Hellö Wörld', encoding='utf-8')

print(str(b, encoding='iso-8859-1'))
print(str(b, encoding='ascii', errors='ignore')) # ignore error
Output
Hellö Wörld
Hell Wrld

In the above example, str(b, encoding='iso-8859-1') converts ö to ö in iso-8859-1 encoding. However, it will throw an error for ASCII encoding, because we specified errors=ignore, it ignores the error and returns a string 'Hell Wrld' by ignoring ö.

Want to check how much you know Python?