Home >>Python String Methods >Python String encode() Method

Python String encode() Method

Python String encode() Method

Python string encode() method is used to encode the string using the specified encoding. If no encoding is specified then UTF-8 will be used for the encoding.

Syntax:
string.encode(encoding=encoding, errors=errors)

Parameter Values

Parameter Description
encoding This is an optional parameter. It defines a String specifying the encoding to use.
errors This is an optional parameter. It defines a String specifying the error method.
Here is an example of Python encode() method:

txt = "My name is Jerry"
x = txt.encode()
print(x)

Output:
b'My name is Jerry'
Example 2:

txt = "Welcome to PHPTPÖÑT"
print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))

Output:
b'Welcome to PHPTP\\xd6\\xd1T'
b'Welcome to PHPTPT'
b'Welcome to PHPTP\\N{LATIN CAPITAL LETTER O WITH DIAERESIS}\\N{LATIN CAPITAL LETTER N WITH TILDE}T'
b'Welcome to PHPTP??T'
b'Welcome to PHPTPÖÑT'

No Sidebar ads