Python Strings decode() method (original) (raw)
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)
`
Output
Encoded 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)
`
Output
Encoded: 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'))
`
Output
Caf? 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!")
`
Output
Encoded 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!'