Python Strings decode() method
Last Updated :
05 Apr, 2025
The decode() method in Python is used to convert encoded text back into its original string format. It works as the opposite of encode() method, which converts a string into a specific encoding format. For example, let's try to encode and decode a simple text message:
Python
s = "Geeks for Geeks"
e = s.encode('utf-8')
print("Encoded text:", e)
print(type(e))
d = e.decode('utf-8')
print(type(d))
print("Decoded text:", d)
OutputEncoded text: b'Geeks for Geeks'
<class 'bytes'>
<class 'str'>
Decoded text: Geeks for Geeks
Explanation:
- s.encode('ut-8') encodes the text into bytes format.
- e.decode('utf-8') decodes the encoded text back to normal unicode format.
Syntax
encoded_string.decode(encoding, errors)
Parameters:
1. encoding: The encoding format used for decoding (e.g., 'utf-8', 'ascii').
2. errors (Optional): Specifies how to handle errors during decoding:
- 'strict' (default): Raises an error for invalid characters.
- 'ignore': Ignores errors and proceeds.
- 'replace': Replaces invalid characters with a placeholder.
Return Type: Returns the original string after decoding.
Working of the Python Decode() Method
The following flowchart shows the working of Python decoding:
Decode()Examples of decode() method:
Example 1: Basic Encoding and Decoding
Encoding converts a string into bytes, and decode() brings it back to its original form.
Python
t = "Hello, Python!"
# Encoding the string into UTF-8
e_t = t.encode('utf-8')
print("Encoded:", e_t)
# Decoding back to original
d_t = e_t.decode('utf-8')
print("Decoded:", d_t)
OutputEncoded: b'Hello, Python!'
Decoded: Hello, Python!
Explanation:
- encode('utf-8') converts the string into bytes format.
- decode('utf-8') restores the original string.
Example 2: Handling Decoding Errors
Sometimes, decoding fails due to incompatible characters. Let's see how different error-handling modes work:
Python
# Encoding with ASCII (supports only basic English characters)
s = "Café"
# Encoding the text in ASCII
enc = s.encode('ascii', errors='replace')
# Decoding with strict mode (raises error)
try:
print(enc.decode('ascii', errors='strict'))
except UnicodeDecodeError as e:
print("Decoding Error:", e)
# Decoding with ignore mode (ignores errors)
print("Ignored Decoding:", enc.decode('ascii', errors='ignore'))
# Decoding with replace mode (replaces errors)
print("Replaced Decoding:", enc.decode('ascii', errors='replace'))
OutputCaf?
Ignored Decoding: Caf?
Replaced Decoding: Caf?
Explanation:
- strict mode raises an error when an unsupported character (é) is found.
- ignore mode removes unsupported characters (é).
- replace mode replaces unsupported characters with a placeholder (?).
Example 3: Real-World Use Case (Password Encoding & Decoding)
Encoding and decoding help secure sensitive data like passwords. Here’s a simple demonstration.
Python
import base64
# User credentials
user = "user1"
passw = "secure@123"
# Encoding password
enc_pass = base64.b64encode(passw.encode('utf-8')).decode('utf-8')
print("Encoded Password:", enc_pass)
# Decoding password for verification
dec_pass = base64.b64decode(enc_pass).decode('utf-8')
print("Decoded Password:", dec_pass)
# Login verification
e_pass = "secure@123"
if e_pass == dec_pass:
print("Login Successful!")
else:
print("Wrong Password!")
OutputEncoded Password: c2VjdXJlQDEyMw==
Decoded Password: secure@123
Login Successful!
Explanation:
- The password is encoded in Base64 to ensure safe storage.
- It is later decoded to verify the login.
Common Use Cases:
- Helps retrieve the original text from an encoded format.
- Essential for handling different character encodings like UTF-8, ASCII, etc.
- Useful in data transmission, security applications, and text processing.
How to use decode in Python 3?
In Python 3, the decode method is used to convert a bytes object into a str (string) object by decoding it from a specific encoding.
Example:
# Define a bytes object
bytes_obj = b'Hello, world!'
# Decode bytes object to string using UTF-8 encoding
string_obj = bytes_obj.decode('utf-8')
print(string_obj) # Output: Hello, world!
Here, decode('utf-8') converts the bytes object from UTF-8 encoding to a string.
What does .decode('utf-8') do?
The .decode('utf-8') method converts a bytes object into a str object using the UTF-8 encoding. UTF-8 is a variable-width character encoding used for text.
Example:
# Define a bytes object with UTF-8 encoding
bytes_obj = b'\xe2\x9c\x94'
# Decode bytes object to string
string_obj = bytes_obj.decode('utf-8')
print(string_obj) # Output: ✓
What is string decoding?
String decoding is the process of converting encoded bytes back into a string. It interprets bytes according to a specified character encoding to produce a readable string.
Example:
# Define a bytes object
bytes_obj = b'Hello'
# Decode bytes object to string
string_obj = bytes_obj.decode('utf-8')
print(string_obj) # Output: Hello
What is an example of decode?
Here’s a basic example of how to use the decode method with a bytes object:
Example:
# Define a bytes object
bytes_data = b'Hello, Python!'
# Decode bytes object to string using UTF-8 encoding
text = bytes_data.decode('utf-8')
print(text) # Output: Hello, Python!
What is encode() in Python?
The encode() method is used to convert a string into a bytes object using a specific encoding. This is the reverse of decode().
Example:
# Define a string
text = 'Hello, world!'
# Encode string to bytes using UTF-8 encoding
bytes_obj = text.encode('utf-8')
print(bytes_obj) # Output: b'Hello, world!'
Additional Example of encode():
# Define a string
text = 'Hello, Python!'
# Encode string to bytes
bytes_data = text.encode('utf-8')
print(bytes_data) # Output: b'Hello, Python!'
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
TCP/IP Model The TCP/IP model is a framework that is used to model the communication in a network. It is mainly a collection of network protocols and organization of these protocols in different layers for modeling the network.It has four layers, Application, Transport, Network/Internet and Network Access.While
7 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read