Python Program to Encode and Decode String
encoded = original_string.encode('utf-8') to encode a string to bytes and decoded = encoded.decode('utf-8') to decode bytes back to a string in Python.Examples
How to Think About It
encode() to convert string to bytes and decode() to convert bytes back to string, specifying the same character encoding like 'utf-8' for both.Algorithm
Code
original_string = 'hello world' encoded = original_string.encode('utf-8') print('Encoded:', encoded) decoded = encoded.decode('utf-8') print('Decoded:', decoded)
Dry Run
Let's trace the string 'hello world' through the encoding and decoding steps.
Original string
original_string = 'hello world'
Encode string
encoded = b'hello world' (bytes representation)
Print encoded
Output: Encoded: b'hello world'
Decode bytes
decoded = 'hello world' (string)
Print decoded
Output: Decoded: hello world
| Step | Variable | Value |
|---|---|---|
| 1 | original_string | 'hello world' |
| 2 | encoded | b'hello world' |
| 4 | decoded | 'hello world' |
Why This Works
Step 1: Encoding the string
The encode() method converts the string into bytes using 'utf-8', which computers can handle easily.
Step 2: Printing encoded bytes
The encoded bytes show with a leading b' to indicate they are byte data, not a normal string.
Step 3: Decoding back to string
The decode() method converts the bytes back to the original string using the same 'utf-8' encoding.
Alternative Approaches
import base64 original = 'hello world' encoded = base64.b64encode(original.encode('utf-8')) print('Encoded:', encoded) decoded = base64.b64decode(encoded).decode('utf-8') print('Decoded:', decoded)
import codecs original = 'hello world' encoded = codecs.encode(original, 'utf-8') print('Encoded:', encoded) decoded = codecs.decode(encoded, 'utf-8') print('Decoded:', decoded)
Complexity: O(n) time, O(n) space
Time Complexity
Encoding and decoding process each character once, so time grows linearly with string length.
Space Complexity
Both encoded bytes and decoded string require space proportional to input size.
Which Approach is Fastest?
Direct encode() and decode() are fastest and simplest; Base64 adds overhead for safe transmission.
| Approach | Time | Space | Best For |
|---|---|---|---|
| utf-8 encode/decode | O(n) | O(n) | Simple string conversion |
| Base64 encoding | O(n) | O(n) | Safe transmission over text-only channels |
| codecs module | O(n) | O(n) | Alternative encoding methods |