Encode and Decode string in python – Encode() & Decode() function

In this section we will learn how to encode and decode string in python. We will be using encode() function to encode a string in python. We will be using decode() function to decode a string in python. Lets look at both with an example.

Encode a String in Python:

Syntax of encode function in python:

str.encode(encoding=’UTF-8′,errors=’strict’)
  • encoding – Encoding codecs to be used
  • errors – Error handling scheme. The default for errors is ‘strict’, meaning that encoding errors raise a UnicodeError. Other possible values are ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ etc

 

Example of Encode function in python:

# Example of string encoding in python

string1="This is example of string encoding and Decoding";
string_encoded=string1.encode('base64','strict');

print "Encoded String is :" +string_encoded;

encode() function uses ‘base64’ codec and error handling scheme as ‘strict’

Note: For more codecs please refer here

So the output will be

Encoded String is :VGhpcyBpcyBleGFtcGxlIG9mIHN0cmluZyBlbmNvZGluZyBhbmQgRGVjb2Rpbmc=

 

Example of Decode function in python:

We will be using the already encoded value as input to the decode function

# example of decoding the string in python

string_decoded=string_encoded.decode('base64','strict');
print "Decoded string is :"+ string_decoded;

Note: you should use the same encoding and error parameters (‘base64’ and ‘strict’) to decode the string.

So the output will be

Decoded string is :This is example of string encoding and Decoding

 

previous Encode and decode a string in python                                                                                                           next Encode and decode a string in python

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.