Home > Article > Backend Development > How to Properly Declare Encoding in Python Source Code?
Python Source Code Encoding Declaration
PEP 263 specifies the method for declaring Python source code encoding. Typically, encoding is declared in the first two lines of a Python file as:
#!/usr/bin/python # -*- coding: utf-8 -*-
However, some files use the following format:
#!/usr/bin/python # -*- encoding: utf-8 -*-
Notably, the second format replaces "coding" with "encoding."
Appropriate File Encoding Declaration
According to official Python documentation, an encoding declaration is recognized if a comment in the first or second line of a script matches the following regular expression:
coding[=:]\s*([-\w.]+)
The recommended form is:
# -*- coding: <encoding-name> -*-
While you can use other text before "coding," it's advisable to use "coding" (without a prefix) for full compatibility with Python documentation recommendations.
Specific Considerations
Beyond Python's requirements, it's important to consider your specific editing software. Some software, like GNU Emacs, recognize the coding form out of the box, while others, like Vim, may require specific adaptations. Ensure that you use the appropriate format for both Python and your editing software.
The above is the detailed content of How to Properly Declare Encoding in Python Source Code?. For more information, please follow other related articles on the PHP Chinese website!