Python uses Chinese comments and outputs Chinese (original)

Source: Internet
Author: User

Just started to learn python, need to annotate Chinese in Python and output Chinese, now try;

Only for preliminary study reference, Master please detour.

-----------------------------------------------------------------------

First step: Enter the following command in the code to execute:

#在Python中显示中文注释和输出中文
A = "Chinese"
Print a

Return Error:

D:\Python27\python.exe "D:\test\ Chinese. Py"
Process started >>>
File "D:\test\ Chinese. Py", line 1
Syntaxerror:non-ascii character ' \xe5 ' in file D:\test\ Chinese. Py on line 1, but no encoding declared; See http://python.org/dev/peps/pep-0263/for details
<<< Process finished. (Exit code 1)
================ Ready ================

In the second step, add the encoding format:

#-*-coding:utf-8–*-

#在Python中显示中文注释和输出中文
A = "Chinese"
Print a

return Result:

D:\Python27\python.exe "D:\test\ Chinese. Py"
Process started >>>
Juan Po
<<< Process finished. (Exit code 0)
================ Ready ================

The program can execute correctly, but the output is still garbled.

The third step, find garbled and processing:

Reason: This is because of win, command line with cp936 encoding, and the above script with Utf-8 encoding, resulting in garbled.

The workaround is to re-decode and encode the characters using the decode and encode functions.

#-*-coding:utf-8–*-
#在Python中显示中文注释和输出中文
A = "Chinese"
Print A.decode (' utf-8 '). Encode (' cp936 ')

return Result:

D:\Python27\python.exe "D:\test\ Chinese. Py"
Process started >>>
Chinese
<<< Process finished. (Exit code 0)
================ Ready ================

Python uses Chinese comments and outputs Chinese (original)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.