Python Chinese encoding
In the previous chapters we have learned how to output "Hello, world!" in Python, but if you output the Chinese character "Hello, the World" you may encounter Chinese coding problems.
If no encoding is specified in the Python file, an error occurs during execution:
#!/usr/bin/pythonprint "你好,世界";
The above program execution output results are:
File "test.py", line 2SyntaxError: 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 above error message shows that we are specifying the encoding, as long as you add #-*-coding:utf-8-*-or #coding =utf-8 at the beginning of the file. Instance (Python 2.0+)
#!/usr/bin/python
#-*-Coding:utf-8-*-
Print "Hello, world";
Run an instance?
The output is:
你好,世界
So if you are in the process of learning that the code contains Chinese, you need to specify the encoding in the header.
Note: python3.x source files use utf-8 encoding by default, so you can parse Chinese normally without specifying UTF-8 encoding.
Note: If you use the editor, you also need to set the encoding for the editor, such as the Pycharm setup step:
- Go to file > Settingsand search for encodingin the input box.
- Locate Editor > File encodings, and set the IDE Encoding and Project Encoding to Utf-8.
Python Chinese encoding