Python String encode() Method
The encode() method encodes a string in the specified encoding format. errors parameter specifies a different error handling scheme.
Python String encode() Syntax
Syntax of the encode() method.
str.encode(encoding='UTF-8',errors='strict')
Python String encode() Parameters
- encoding — The encoding to use, e.g., UTF-8.
- errors — Set different error handling schemes. The default is ‘strict’, meaning that an encoding error causes a UnicodeError. Other possible values are ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ and any value registered with codecs.register_error(). any value.
Python String encode() Return Value
This method returns the encoded string, which is a bytes object.
Python String encode() Example#1
Print the available encoding schemes.
from encodings.aliases import aliases
# Printing list available
print("The available encodings are : ")
print(aliases.keys())
Output:
Python String encode() Example#2
Encode the string.
string = "¶"
# trying to encode using utf-8 scheme
print(string.encode('utf-8'))
Output:
Python String encode() Example#3
The Python String encode() method will throw a UnicodeEncodeError if the wrong encoding scheme is used.
string = "¶"
# trying to encode using ascii scheme
print(string.encode('ascii'))
Output:
Python String encode() Example#4
Use the errors
parameter to ignore errors during encoding.
string = "123-¶"
# ignore if there are any errors
print(string.encode('ascii', errors='ignore'))
Output: