Skip to main content
Encode and Decode String in Python

Encode and Decode String in Python

In this article, We’ll discuss encode and decode methods in Python. These methods help to encode and decode the input string according to the encoding specified. We’ll take a closer look at these two functions.

Python Encode and Decode String

In Python, encoding and decoding a string can be done using the encode and decode methods provided by the str class.

You can also checkout other python tutorials:

How To Encode String in Python

The encode() method in Python is used to encode a string using the encoding that is specified. Bytes is returned by this function. Some commonly used encodings are UTF-8, UTF-16, and ASCII. If no encoding is specified, the default is “utf-8.”

The Syntax:

input_string.encode(encoding, errors)

Where params:

  • input_string : This is source string.
  • encoding : This is the type of encoding.
  • errors : This contains have strict, ignore, replace and backslashreplace.

This method return result as an object:

Simple Example to Encode string:

s = 'Pythonpip'
bytes_encoded = s.encode()
print(type(bytes_encoded))

In the above example, the encode method is used to convert the s to a byte string using the UTF-8 encoding.

Output :

b'Pythonpip'

The b character in the output indicates that the encoded string is a byte string.

How To Decode String in Python

This is the reverse of encode() method. The decode() method helps to convert a stream of bytes to a string object.

The Syntax:

byte_seq.decode()

The decode() converts bytes to a Python string.

Decode the byte string to a string:

bytes_encoded = b'Pythonpip'
decoded_string = bytes_encoded.decode()
print(decoded_string)

Output :

Pythonpip

Leave a Reply

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