Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python Chinese code


May 10, 2021 Python2


Table of contents


Python Chinese code

In the previous sections we learned how to output "Hello, World!" with Python, no problem in English, but if you output the Chinese character "Hello, the world" you may run into Chinese coding problems.

If the encoding is not specified in the Python file, an error will occur during the execution process:

#!/usr/bin/python
print "你好,世界";

The output of the above program execution is:

  File "test.py", line 2
SyntaxError: Non-ASCII character '\xe4' in file test.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

The error message above shows that we are encoding for the specified, and the solution is to simply add the word "-coding: UTF-8 - or #coding-utf-8" at the beginning of the file.

Example (Python 2.0 plus)

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

print "Hello, World";

Run an instance . . .

The output is:

你好,世界

So if you're learning, the code contains Chinese, you need to specify the code at the head.

Note: Python 3.X source files use utf-8 encoding by default, so the Chinese can be resolved without specifying UTF-8 encoding.

Note: If you use the editor, you also need to set up the editor's encoding, such as the Pycharm setup step:

  • Go to file and Settings and search for encoding in the input box.
  • Find Editor and File encodings and set IDE Encoding and Project Encoding Encoding to utf-8.
Python Chinese code