Python String - encode() Method
The Python encode() method returns the encoded version of the given string, using the specified encoding. If no encoding is specified, UTF-8 will be used.
Syntax
string.encode(encoding, errors)
Parameters
encoding |
Optional. Specify the encoding to use. Default is UTF-8. |
errors |
Optional. Specify the error method. Legal values are:
|
Return Value
Returns the encoded version of the given string.
Example:
In the example below, encode() method returns the encoded version of the string called MyString.
MyString = "Pythön!" print(MyString.encode("ascii", "backslashreplace")) print(MyString.encode("ascii", "ignore")) print(MyString.encode("ascii", "namereplace")) print(MyString.encode("ascii", "replace")) print(MyString.encode("ascii", "xmlcharrefreplace"))
The output of the above code will be:
b'Pyth\\xf6n!' b'Pythn!' b'Pyth\\N{LATIN SMALL LETTER O WITH DIAERESIS}n!' b'Pyth?n!' b'Pythön!'
❮ Python String Methods