0
0
PythonHow-ToBeginner · 3 min read

How to Use Encode and Decode in Python String

In Python, use string.encode() to convert a text string into bytes using a specified encoding like UTF-8. Use bytes.decode() to convert bytes back into a string with the correct encoding.
📐

Syntax

Encoding: encoded_bytes = string.encode(encoding='utf-8') converts a string to bytes using the chosen encoding.

Decoding: decoded_string = bytes.decode(encoding='utf-8') converts bytes back to a string using the same encoding.

  • encoding is usually 'utf-8', but can be others like 'ascii'.
  • Encoding turns text into bytes for storage or transmission.
  • Decoding turns bytes back into readable text.
python
text = 'Hello, world!'
encoded = text.encode('utf-8')
decoded = encoded.decode('utf-8')
💻

Example

This example shows how to encode a string into bytes and then decode it back to a string.

python
text = 'Hello, Python!'
print('Original string:', text)

encoded_bytes = text.encode('utf-8')
print('Encoded bytes:', encoded_bytes)

decoded_string = encoded_bytes.decode('utf-8')
print('Decoded string:', decoded_string)
Output
Original string: Hello, Python! Encoded bytes: b'Hello, Python!' Decoded string: Hello, Python!
⚠️

Common Pitfalls

Common mistakes include:

  • Using different encodings for encode and decode, causing errors or wrong characters.
  • Trying to decode a string instead of bytes, which raises an error.
  • Not handling characters outside the chosen encoding (like non-ASCII in 'ascii').
python
wrong_bytes = 'Hello'.encode('utf-8')
# Wrong: decoding with a different encoding
# decoded_wrong = wrong_bytes.decode('ascii')  # This can cause errors

# Correct way:
decoded_correct = wrong_bytes.decode('utf-8')
print(decoded_correct)
Output
Hello
📊

Quick Reference

MethodPurposeExample
string.encode(encoding='utf-8')Convert string to bytes'text'.encode('utf-8')
bytes.decode(encoding='utf-8')Convert bytes to stringb'text'.decode('utf-8')

Key Takeaways

Use string.encode() to convert text to bytes with a specified encoding.
Use bytes.decode() to convert bytes back to text using the same encoding.
Always match the encoding used in encode and decode to avoid errors.
Encoding is needed for storing or sending text as bytes.
Decoding is needed to read bytes back as human-readable text.