Python String encode() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

The encode() method in Python encodes a string using the specified encoding. If no encoding is specified, UTF-8 encoding will be used.

Syntax of encode() method

string.encode(encoding, errors)

encoding: Encoding to use(optional)
          Default value is UTF-8.
errors:	Required Error method(Optional)

Check out the list of standard encodings with Python.

You can use the following error values.

  1. backslashreplace - use a backslash instead of the character that could not be encoded
  2. ignore - ignore the characters that cannot be encoded.
  3. namereplace - replace the character with a text explaining the character.
  4. strict - Default, will raise an error on failure.
  5. replace - replace the character with a question mark.
  6. xmlcharrefreplace - replace the character with an xml character.

Python is only going to use these above error types, if it runs into some error while encoding.

Example 1 - Simple encoding to UTF-8


str1 = "I like Pylenin"



b'I like Pylenin'
Example 2 - Encoding a Non-ASCII string to ASCII


str1 = "Pylenin like �pples"

print(str1.encode('ASCII', errors='backslashreplace'))
print(str1.encode('ASCII', errors='ignore'))
print(str1.encode('ASCII', errors='namereplace'))
print(str1.encode('ASCII', errors='replace'))
print(str1.encode('ASCII', errors='xmlcharrefreplace'))


b'Pylenin like \\xe4pples'
b'Pylenin like pples'
b'Pylenin like ?pples'
b'Pylenin like äpples'

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide