Python Chinese Encoding processing method

Source: Internet
Author: User

Decode early, Unicode everywhere, encode late

1. when entering or declaring a string, use the Decode method as soon as possible to convert the string into Unicode encoding format;

2. then use the string in the program when using Unicode format for processing, such as string concatenation, string substitution, get the length of the string and other operations;

3. Finally, in the output string (console/web/file), through the Encode method to convert the string into the encoding format you want, such as Utf-8.

Input (str,utf-8)--decode--> operation Unicode--encode--> output (str, utf-8)

#-*-coding:gb2312#-*-

__author__= ' Administrator '

Importchardet

#变量若声明前面不加u则在python2. x in ASCII character set with type str

ss1= "I am Chinese"

Printtype (SS1) #<type ' str ' >

Printchardet.detect (SS1) #{' confidence ': 0.99, ' encoding ': ' GB2312 '}

#前面加u, with Unicode character set, type Unicode

Ss2=u ' Chinese '

Printtype (SS2) #<type ' Unicode ' >

#调用decode函数, convert str to Unicode

Ss3=ss1.decode (' gb2312 ')

Printtype (SS3) #<type ' Unicode ' >

#调用encode, convert Unicode to STR

Ss4=ss3.encode (' UTF8 ')

Printtype (SS4) #<type ' str ' >

Printchardet.detect (SS4) #{' confidence ': 0.938125, ' encoding ': ' Utf-8 '}

Python Chinese Encoding processing method

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.