Latest web development tutorials

Python coding Chinese

Python coding Chinese

Previous chapters we have learned how to use Python output "Hello, World!", English no problem, but if you output Chinese characters "Hello, World" is likely to encounter Chinese coding problem.

Python file if the encoding is not specified in the implementation process will be given:

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

The above program execution output 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

Python in the default encoding format is an ASCII format, did not modify the encoding format when characters can not print correctly, so when reading Chinese error.

Solution is just the beginning of the file on # - * - coding: UTF- 8 - * - or # coding = utf-8 on the list.

Examples (Python 2.0+)

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

print "Hello, world";

Running instance »

The output is:

你好,世界

So if we re-learning process, the code contains Chinese, you need to specify the encoding in the header.

Note: Python3.X source file default utf-8 encoding, so it can properly resolve the Chinese, without specifying UTF-8 encoding.

Note: If you use the editor, and the need to set a good code editor, such as Pycharm setup steps:

  • Enter the file> Settings, search for encoding in the input box.
  • Found Editor> File encodings, and the IDE Encoding Project Encoding is set to utf-8.