The str()
method is Python is a built-in method which is used to represent strings in a printable manner. We will see its syntax, parameters, return type and understand how it works.
Syntax of the str
method
The str
method can have two different syntaxes. Depending on the requirement, either of these can be used.
1. str(object = '')
When the object is provided, under the hood, it calls the __str__
method of that object type. In case the __str__
method of that object can't be found, it calls the __repr__
method of the object.
2. str(object = b'', encodings = '', errors = '')
The str
method can take 3 parameters.
-
The first parameter is the object which needs to be represented in a neat manner.
-
The second parameter talks about the encoding of the object, this could be utf-8, latin, ascii or other encodings.
-
The third parameter is the response in case of the decoding failing. 6 types of error options are available. They have been listed below:
-
strict - It is a default response that raises a UnicodeDecodeError error when the decoding fails.
-
ignore - This option ignores the unicode which can't be encoded.
-
replace - This option replaces the unicode which can't be encoded into a question mark (?).
-
xmlcharrefreplace - This option inserts XML character reference instead of placing the Unicode which can't be encoded.
-
backslashreplace - This option inserts a \uNNNN sequence instead of placing the Unicode which can't be encoded.
-
namereplace - This option inserts a \N{...} escape sequence instead of placing the Unicode which can't be encoded.
The 'b' in the object parameter refers to byte or bytearray, which is the format in which the object needs to be passed.
How the str
method works when only the object
parameter is provided:
print(str(12))
print(str('12'))
print(str('Studytonight'))
print(str(b'Studytonight'))
Output:
12
12
Studytonight
b'Studytonight'
str
method with encodings and errors parameters:
The below code encodes a string that has a character that can't be encoded with utf-8 encoding (ö). But since the parameter errors
have been set to ignore, that character is ignored and the rest of the string is presented in a neat way.
str_to_format = bytes('Studytönight', encoding='utf-8')
print(str(str_to_format, encoding='ascii', errors='ignore'))
print(str(str_to_format, encoding='ascii')) # When the 'errors' parameter is not set to ignore
Output:
Studytonight
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 6: ordinal not in range(128)
Note: When the encodings and errors are provided, the object parameter should be a byte-like object (like a byte or an array)
Conclusion:
In this post, we understood how the str method works. Don't forget to set the parameters encoding and errors to different values and understand the output.