Character Encoding Of Python Source Files

By default, Python source files are encoded in UTF-8. In this way, the characters of most languages in the world can be used in string literal, variable, or function name and comment at same time,  although the standard library uses only regular ASCII characters for variable or function names, any portable code should follow this convention. To display these characters correctly, your editor must recognize UTF-8 encoding and use a font that supports all characters in the opened python source file.

1. How To Use Special Text Encoding In Python Source Code File.

If you do not use the default encoding, to declare the encoding used by the file, write a special comment on the first line of the file, the syntax is as follows. The encoding value can be any codec supported by python.

# -*- coding: encoding -*-

For example, to declare using UTF-8 encoding, your source code file should be written as below.

# -*- coding: utf-8 -*-

An exception to the first line rule is that the source code starts with the UNIX “shebang” line. In this case, the encoding declaration is written on the second line of the file. for example.

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.