Python String Encode Decode Exercise

Write a program in Python to encode and decode the following string.

Hello Friend! Welcome to this tutorial.

Solution


Python encode()

Python has predefined encode() method to encode the string. It comes with a number of built in codecs, like - ascii, big5, latin_1, utf_7, utf_8 etc. If no any encoding codec specified, by default UTF-8 will be used.


Syntax of Python Encoding
string.encode(encoding, errors) 

Here, both encoding and errors are optional parameters. The encoding parameter by default take UTF-8.


Python decode()

Python has predefined decode() method to decode the string. This works opposite of encode. It accepts the encoding of the encoded string to decode it and returns the original string.

This is the following solution to encode and decode the given string -

str = "Hello Friend! Welcome to this tutorial."
 
# string encoding 
str_enc = str.encode('base64', 'strict')
 
print "The encoded string is : ",
print str_enc
 
# string decoded
print "The decoded string is : ",
print str_enc.decode('base64', 'strict')

Output of the above code
Python Encode Decode





Related Articles

Python program for Prime Number
Odd Even Program in Python
Python program to convert Celsius to Fahrenheit
Python Convert XML to CSV
Python Text to Speech
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml




Read more articles


General Knowledge



Learn Popular Language