Coding problems with Python

Source: Internet
Author: User

Unicode

  What is Unicode:unicode is a secret weapon that computers can support in multiple languages on the planet. Unicode uses one or more bytes to represent one character.

Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0xe6 in position 0:ordinal not in range (128) the solution and principle of the problem:

The problem is to encode Chinese in python2, which means that the maximum length of ASCII encoding is 128, which is beyond this range when decoding Chinese. Because the program wants to encode Chinese, it first decodes the Chinese into Unicode (the system default is ASCII).

Workaround:

First, in the script before the default encoding method of the file is UTF8

1 # -*-coding:utf-8-*- 2 # !/usr/bin/env python 3 Import SYS 4 Reload (SYS)                     #  re-import 5 sys.setdefaultencoding ('UTF8  ')  #  Set the default encoding to UTF8

  

Second, in the Chinese encoding forward decoding to UTF8 format

 1  #   Error code  2  str =  "  Chinese string  "  3  str_out = Str.encode ( '  utf8   ) 
1 # the normal code 2 " Chinese string " 3 str = str.decode ('UTF8')4 str_out = Str.encode ('  UTF8')

Specify the format of the string before defining the Chinese string, for example:

1 # Specify string encoding format when defining 2 str = u" Chinese string "3 str_out = Str.encode ('UTF8') )

    

Coding problems with Python

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.