Python 3 – String encode() Method
In Python 3, the encode() method is used to convert a Python string into a bytes object. The bytes object can then be stored or transmitted over the network.
The encode() method takes one argument, which is the encoding type. The most commonly used encoding types are ASCII and UTF-8.
Syntax
string.encode(encoding='UTF-8',errors='strict')
Parameters
- encoding (optional): The name of the encoding to use. Default is UTF-8.
- errors (optional): The error handling scheme to use for encoding errors. The default is ‘strict’ which causes a UnicodeError to be raised on any encoding errors.
Return Value
The encode() method returns a bytes object.
Example 1: Encode a String Using the default UTF-8 Encoding
# encoding a string with UTF-8
text = "Hello, World!"
text_utf8 = text.encode()
print(text_utf8)
Output:
b'Hello, World!'
In the example above, we encoded the string text
using the default UTF-8 encoding. The resulting text_utf8
is a bytes object.
Example 2: Encode a String Using ASCII Encoding
# encoding a string with ASCII
text = "Hello, World!"
text_ascii = text.encode(encoding='ASCII')
print(text_ascii)
Output:
b'Hello, World!'
In the example above, we encoded the string text
using ASCII encoding. The resulting text_ascii
is a bytes object.
Example 3: Handle Encoding Errors
# error handling
text = "Hello, World! 😊"
try:
text_ascii = text.encode(encoding='ASCII')
except UnicodeEncodeError as e:
print(f"Error: {e}")
Output:
Error: 'ascii' codec can't encode emoji in position 13: ordinal not in range(128)
In the example above, we tried to encode a string containing emoji characters using ASCII encoding. Since ASCII does not support these characters, a UnicodeEncodeError was raised.
Conclusion
The encode() method is an important function for encoding Python strings into bytes objects so that they can be stored or transmitted over a network. It is important to choose the appropriate encoding type and handle any encoding errors that may occur.