Python String encode() Method is used to encode a string into a specified encoding format. If no encoding is specified, UTF-8 will be used as the default.
Syntax
string_var.encode(encoding, errors)
Parameters
- Encoding: Type of encoding in which the string parameters and shown.
- Errors: Response was given when the encoding failed. There are about six encoding error responses.
'backslashreplace'
It uses a backslash instead of the character that could not be encoded 'ignore'
It ignores the characters that cannot be encoded 'namereplace'
It replaces the character with a text explaining the character 'strict'
Default raises an error on failure 'replace'
It replaces the character with a question mark 'xmlcharrefreplace'
It replaces the character with an XML character
Return value
It returns the encoded string.
In case of failure, it raises the UnicodeDecodeError exception.
Visual Representation
Example 1: Basic Usage
str1 = 'Rönaldo!!'
str2 = str1.encode()
print(str2)
Output
b'R\xc3\xb6naldo'
You can see the UTF-8 encoded version of the string in the output. In UTF-8, the “ö” character is encoded as the byte sequence \xc3\xb6.
Example 2: With ASCII encoding
str1 = 'Rönaldo!!'
print("Original string : " ,str1)
# replace error
print(str1.encode("ascii", "replace"))
Output
Original string : Rönaldo!!
b'R?naldo!!'
As you can see in the output, “ö” character cannot be represented in ASCII and is therefore replaced with a ? character.
Example 3: Using error parameter
str = 'Rönaldo!!'
print('The string is:', str)
# ignore error
print('The encoded version (with ignore) is:', str.encode("ascii", "ignore"))
# replace error
print('The encoded version (with replace) is:', str.encode("ascii", "replace"))
Output
The string is: Rönaldo!!
The encoded version (with ignore) is: b'Rnaldo!!'
The encoded version (with replace) is: b'R?naldo!!'