Menu Close

Python String encode() Method

python string encode

In this tutorial, you have learned the Python string encode() method to encode the string along with examples.
Python string encode() method is a string method that is used to encode the string using the specified encoding.

In the previous tutorial, we have seen the Python string upper() method to convert lowercase to uppercase.

Python String encode() Method

The encode function in Python is a string function that is used to encode a string using specified encoding, If any encoding not specified, It will use UTF-8 by default.

Syntax

The syntax of python string encode method is:

Parameter:

python string encode method accepts two parameters.

  • encoding:- Optional. A string specifying the encoding to use. Be default UTF-8.
  • errors:- There are various types of errors.

    backslashreplace – use the backslash instead of the character that could not be encoded.
    ignore– ignore the character that can not be encoded.
    namereplace– replaces the character with text explaining character.
    strict – Default, raise an error of failure.
    replace – replace the character with a question mark.
    xmlcharrefreplace – replaces the character with an XML character

Python string encode example

Here we will use some examples to understand encode function in python.

Example

txt = "This is å educational portål"
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'This is \xe5 educational port\xe5l'
b'This is  educational portl'
b'This is \N{LATIN SMALL LETTER A WITH RING ABOVE} educational port\N{LATIN SMALL LETTER A WITH RING ABOVE}l'
b'This is ? educational port?l'
b'This is å educational portål'

Conclusion:

In this tutorial, you have learned the Python string encode function to encode the string using a specified string.
if any encoding not specified, It will use by default UTF-8.

I hope this tutorial will help you. If you like this article, please share it with your friends who want to learn Python programming.

Other string methods

For More Information:- Click Here

Python String strip() Method
Python String zfill() Method:

Was this post helpful?

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *