SoFunction
Updated on 2024-10-30

Basic Chinese encoding problem solved in the version

Python outputs "Hello, World!", which is fine in English, but if you output the Chinese character "Hello, World" you may run into Chinese encoding problems.
Python files that do not specify an encoding will report an error during execution:

#!/usr/bin/python
print "Hello, world.";


The output of the above program execution is:
 

 File "", line 2
SyntaxError: Non-ASCII character '\xe4' in file  on line 2, but no encoding declared; see /peps/ for details

The default encoding format in Python is ASCII format, which cannot print Chinese characters correctly without modifying the encoding format, so it will report an error when reading Chinese.
The solution is to add # -*- coding: UTF-8 -*- or #coding=utf-8 at the beginning of the file.
Examples (Python 2.0+)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

print "Hello, world.";


The output result is:

How are you?,global

So if you then learn the process, the code contains Chinese, you need to specify the encoding in the header.
Note: The source code file uses utf-8 encoding by default, so you can parse Chinese normally without specifying UTF-8 encoding.