Python OOPs


Python SQLite


Examples


Others


String encode() method in Python


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

Syntax
string.encode(encoding,errors)
Parameters Description
encoding (Optional) The encoding type to be used. Default is UTF-8. Standard encodings
errors (Optional) Set the errors mode. Default value is strict.
  • strict - Raises an error on failure.
  • ignore - Ignores the unencodable unicode.
  • replace - Replaces the unencodable unicode to a questionmark.
  • xmlcharrefreplace - Replaces the unencodable unicode with an xml character.
  • backslashreplace - Replaces the unencodable unicode with a backslash.
  • namereplace - Replaces the unencodable unicode with a text explaining the character.
Example 1 :
txt="Hello World"
print(txt.encode())
print(txt.encode(encoding="ascii"))
print(txt.encode(encoding="UTF-16"))

Output

b'Hello World'
b'Hello World'
b'\xff\xfeH\x00e\x00l\x00l\x00o\x00 \x00W\x00o\x00r\x00l\x00d\x00' 
Example 2 : Encoding with error parameter
txt="Hellö World"
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))
print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="namereplace"))

Output

b'Hell World'
b'Hell? World'
b'Hellö World'
b'Hell\\xf6 World'
b'Hell\\N{LATIN SMALL LETTER O WITH DIAERESIS} World' 

Python String Methods