Python | str constructor
Start your free 7-days trial now!
Python's str(~)
constructor returns a string version of the object.
Parameters
1. object
| object
The object to convert into a string.
2. encoding
link | encoding type
| optional
The encoding of the provided object. Default is utf-8
.
3. errors
link | error method
| optional
Specifies how to handle errors. Default is strict
.
Type | Description |
---|---|
| Raise |
| Ignore the malformed data and continue without further notice. |
| Replace with a suitable replacement marker for encoding. |
| Replace with the appropriate XML character reference. |
| Replace with backslashed escape sequences. |
| Replace with |
Return value
A string version of the object. If no object is provided, an empty string is returned.
Examples
To return a string version of 15
:
Encoding parameter
To specify encoding of 'utf-8'
:
# Create a bytes object and store it to variable yy = bytes('marché', encoding='utf-8')str(y, encoding='utf-8')
'marché'
The bytes object y
which was encoded using utf-8
can successfully be decoded and converted to a string.
Errors parameter
To specify 'replace'
error method and decode using 'ascii'
:
# Create a bytes object and store it to variable zz = bytes('marché', encoding='utf-8')str(z, encoding='ascii', errors='replace')
'march��'
It is not possible to decode é
in ASCII hence '�'
replacement marker is used instead of raising an error.
To decode 'marché'
using 'ascii'
and 'strict'
error method:
# Create a bytes object and store it to variable zz = bytes('marché', encoding='utf-8')str(z, encoding='ascii', errors='strict')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5
It is not possible to decode é
in ASCII and as we have specified 'strict'
mode to handle errors a UnicodeDecodeError
is raised.