Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Chinese Encoding

Python Chinese Encoding

In the previous chapters we learned how to output with Python "Hello, World!", and English is no problem, but if you output Chinese characters "Hello, World" you may encounter Chinese encoding issues.

If no encoding is specified in a Python file, an error will occur during execution:


#!/usr/bin/python

print ("你好,世界")

The output of the above program 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 default encoding format in Python is ASCII. Without changing the encoding format, Chinese characters cannot be printed correctly, so an error occurs when reading Chinese.

The solution is simply to add # -- coding: UTF-8 -- or # coding=utf-8 at the beginning of the file

Note:# coding=utf-8 's = Do not put spaces on either side of the = sign.

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

print

(

"

Hello, World

"

)

Run Example »

The output is:


你好,世界

So if your code contains Chinese while you are learning, you need to specify the encoding at the top.

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

Note:If you use an editor, you also need to set the py file storage format to UTF-8, otherwise an error message similar to the following will appear:


SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte

PyCharm setup steps: