Python Chinese encoding

Source: Internet
Author: User

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

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.