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:
-Method.png)
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 - Strings encode() method
String encode() method in Python is used to convert a string into bytes using a specified encoding format. This method is beneficial when working with data that needs to be stored or transmitted in a specific encoding format, such as UTF-8, ASCII, or others. Let's start with a simple example to unde
3 min read
Python String Methods
Python string methods is a collection of in-built Python functions that operates on strings. Note: Every string method in Python does not change the original string instead returns a new string with the changed attributes. Python string is a sequence of Unicode characters that is enclosed in quotati
6 min read
String lower() Method in Python
lower() method in Python converts all uppercase letters in a string to their lowercase. This method does not alter non-letter characters (e.g., numbers, punctuation). Let's look at an example of lower() method: [GFGTABS] Python s = "HELLO, WORLD!" # Change all uppercase letters to lowercas
3 min read
Python String maketrans() Method
maketrans() method in Python is a powerful tool for creating mapping tables that specify how specific characters in a string should be replaced. This method is often used in conjunction with the translate() method to perform character replacements efficiently. Let's understand with help of an exampl
3 min read
Python String lstrip() method
The lstrip() method removes leading whitespace characters from a string. We can also specify custom characters to remove from the beginning/starting of the string. Let's take an example to remove whitespace from the starting of a string. [GFGTABS] Python s = " Hello Python!" res = s.lstrip
2 min read
Python | os.fsdecode() method
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.fsdecode() method in Python is used to decode the specified filename from the
1 min read
Python String format_map() Method
Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key's value. Syntax: string.format_map(z) Parameters: Here z is a variable in which the input dictionary is stored and string is the key of the input dictionary. input_dict: Takes a single parame
2 min read
Python string swapcase() Method
swapcase() method in Python is used to return a new string where all the uppercase characters in the original string are converted to lowercase, and all the lowercase characters are converted to uppercase. Let's us understand this with the help of an example: [GFGTABS] Python s = "I love Python
2 min read
String capitalize() Method in Python
The capitalize() method in Python is used to change the first letter of a string to uppercase and make all other letters lowercase. It is especially useful when we want to ensure that text follows title-like capitalization, where only the first letter is capitalized. Let's start with a simple exampl
2 min read
Python String upper() Method
upper() method in Python is a built-in string method that converts all lowercase letters in a string to uppercase. This method is simple to use and does not modify the original string; instead, it returns a new string with the modifications applied. Example: [GFGTABS] Python s = "learn python w
2 min read