UTF-8 is a widely used character encoding that can represent text from many languages. Configure the editor consistently so saved source files read correctly.
Understanding the Concept
Python 3 source files are UTF-8 by default unless an encoding declaration says otherwise. PyCharm normally supports UTF-8 and offers file-encoding settings. Python also standardizes UTF-8 as the default text-file encoding in more runtime contexts, but being explicit about file encodings is still good practice for portable programs. If a file shows strange symbols instead of accented characters, its stored bytes may be interpreted using the wrong encoding.
When and Why You Would Use This
For ordinary .py files, keep UTF-8 and avoid adding encoding declarations unnecessarily. When opening data files, encoding="utf-8" documents your intent clearly and is useful for code shared with people on other systems.
Practical Example
message = "Café — Python"
print(message)
print(message.encode("utf-8"))
Understanding the Example
The first line displays readable Unicode text. The second shows a bytes representation of the UTF-8 encoding; accented characters and punctuation use multibyte sequences. PyCharm should save this file as UTF-8 so the source and displayed text remain consistent.
Example Output
Café — Python
b'Caf\xc3\xa9 \xe2\x80\x94 Python'
Try It Yourself
Add text containing an accented character, save it as UTF-8, reopen the file, and confirm the character remains correct.
Common Beginner Mistakes
- Assuming text and bytes are the same thing. Encoding converts between Unicode text and a byte representation.
- Changing file encoding to fix a font-display issue without checking the actual bytes.
- Reading external text files without knowing their encoding.
Key Takeaways
- Use UTF-8 for Python source and new text-data files.
- Editor encoding and runtime text encoding are related but distinct settings.
- Explicit encoding arguments make file operations clearer.