encode() String Method in Python with Examples

encode() method encode the string using the codec registered for encoding.

Syntax: encode() String Method

encode(self, /, encoding='utf-8', errors='strict')

encode() Syntax Explanation

encoding : The encoding in which to encode the string.

errors : The error handling scheme to use for encoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

Example 1: encode() String Method


message = 'Welcome to Python!'
print(message.encode())

Output

b'Welcome to Python!'

Example 2: encode() String Method


message = 'मुटु जलिरहेछ।'
print(message.encode())

Output

b'\xe0\xa4\xae\xe0\xa5\x81\xe0\xa4\x9f\xe0\xa5\x81 \xe0\xa4\x9c\xe0\xa4\xb2\xe0\xa4\xbf\xe0\xa4\xb0\xe0\xa4\xb9\xe0\xa5\x87\xe0\xa4\x9b\xe0\xa5\xa4'


Related String Methods