Python String encode() Method

Encodes the string to the specified encoding

Usage

The encode() function encodes the string to the specified encoding and returns it as a bytes object.

The string is encoded to UTF-8 by default.

Syntax

string.encode(encoding,errors)

Python string encode() method parameters
ParameterConditionDescription
encodingOptionalSpecifies encoding
errorsOptionalSpecifies different error handling scheme
‘strict’ – (Default) raises an UnicodeError exception on failure
‘backslashreplace’ – the unencodable character is replaced by a backslash
‘ignore’ – the unencodable character is ignored
‘namereplace’ – the unencodable character is replaced by its name
‘replace’ – the unencodable character is replaced by questionmark
‘xmlcharrefreplace’ – the unencodable character is replaced by an xml character

Basic Example

# Encode the string to UTF-8
S = 'Das straße'
x = S.encode()
print(x)
# Prints b'Das stra\xc3\x9fe'

Unicode Encode Error Handling

Let’s try to encode the German words ‘Das straße‘, which translates to ‘The street‘ in english.

S = 'Das straße'

Following example shows different error handling scheme implementations by using errors parameter.

x = S.encode(encoding='ascii',errors='backslashreplace')
print(x)
# Prints b'Das stra\\xdfe'

x = S.encode(encoding='ascii',errors='ignore')
print(x)
# Prints b'Das strae'

x = S.encode(encoding='ascii',errors='namereplace')
print(x)
# Prints b'Das stra\\N{LATIN SMALL LETTER SHARP S}e'

x = S.encode(encoding='ascii',errors='replace')
print(x)
# Prints b'Das stra?e'

x = S.encode(encoding='ascii',errors='xmlcharrefreplace')
print(x)
# Prints b'Das straße'

x = S.encode(encoding='UTF-8',errors='strict')
print(x)
# Prints b'Das stra\xc3\x9fe'