Python settings Utf-8 as the default encoding

Source: Internet
Author: User

Coding problems have always been a headache when programming with Python, and the program often encounters the following error message:

Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0x?? In position 1:ordinal not in range (128)

This is because Python's default encoding is ASCII at the time of installation, and when non-ASCII encoding occurs in the program, Python processing often reports the error above.

For the above problem, there are generally 2 kinds of treatment methods:

Method 1:

Add the following code block at the beginning of the Python code:

[Python]View PlainCopy
    1. Import Sys
    2. Reload (SYS)
    3. sys.setdefaultencoding (' UTF8 ')

This method is temporary and only takes effect when the program executes, and the system default encoding does not change.

Method 2:

The default encoding for Python installation is ASCII, and the default encoding can be viewed by sys.getdefaultencoding (). In order to solve the problem at once, we can modify Python's default encoding. Here's how:

The first step:

Create a new sitecustomize.py file under the Lib\site-packages folder in the Python installation directory

Step Two:

Fill in the following code in sitecustomize.py


    1. # Encoding=utf8
    2. Import Sys
    3. Reload (SYS)
    4. sys.setdefaultencoding (' UTF8 ')

Step three: Restart Python and view the default encoding via Sys.getdefaultencoding (), when the result is ' UTF8 '

Python settings Utf-8 as the default encoding

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.