Python str() Method
The str()
constructor method returns an object of the str
class with the specified value.
Syntax:
str(object, encoding, errors)
Parameters:
- object: (Optional) The int, float, boolean, or any other object whose value needs to be converted to a string.
- encoding: (Optional) Encoding of the specified object. Defaults is UTF-8.
- errors: (Optional) Response when decoding fails. Defaults to 'strict'
Return Value:
Returns a string.
The following example converts an integer to string.
numstr = str(10)
print(numstr)
print(type(numstr))
10
<class 'str'>
The following converts different values to string.
fstr = str(10.5)
bstr = str(True)
cstr = str(3+4j)
print(fstr)
print(bstr)
print(cstr)
'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.
print(str(b'Hello'))
"b'hello'"
The following converts bytes to string.
b = bytes('Hellö Wörld', encoding='utf-8')
print(str(b, encoding='iso-8859-1'))
print(str(b, encoding='ascii', errors='ignore')) # ignore error
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 ö
.