1 min read

Python Source Code Encoding

By default, Python 3 source files are treated as encoded in UTF-8. This allows you to use Unicode characters in string literals, comments, and variable names without any special declarations.

Default Encoding

In Python 3, the default encoding is UTF-8.

# This works by default in Python 3
s = "Hello world 🌍"
print(s)

Declaring Encoding

If you need to use a different encoding (e.g., for legacy reasons or specific requirements), you must declare it at the top of the file. This is done using a special comment line.

The syntax is defined in PEP 263. It must match the regular expression coding[:=]\s*([-\w.]+).

Syntax

The encoding declaration must appear on the first or second line of the file.

# -*- coding: encoding_name -*-

Or:

# coding=encoding_name

Examples

Using latin-1 (ISO-8859-1):

# -*- coding: latin-1 -*-

currency = "£" # In latin-1, this might be encoded differently than UTF-8

Interaction with Shebang

If a script has a shebang line (e.g., #!/usr/bin/env python3), the encoding declaration should go on the second line.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

print("Hello")

programming/python/python