Python string garbled problem __ garbled problem

Source: Internet
Author: User

The representation of a string inside Python is a Unicode encoding.


As a result, in encoding conversions, Unicode is usually used as an intermediate encoding, in which other encoded strings are decoded (decode) into Unicode, and then from Unicode encoding (encode) to another encoding.


The role of decode is to convert other encoded strings into Unicode encoding, such as String1.decode (' Utf-8 '), which means converting the UTF-8 encoded string string1 to Unicode encoding.

The role of encode is to convert Unicode encoding to other encoded strings, such as String2.encode (' Utf-8 '), which means converting a Unicode-encoded string string2 to a utf-8 encoding.





If a string is already Unicode, then the decoding is an error, so it is usually judged by whether the encoding is Unicode:
Isinstance (String3, Unicode) #用来判断string3是否为unicode编码
String3 in the form of non-Unicode encoding can also be used to encode the error.


#获得系统的默认编码
#!/usr/bin/env python
#coding =utf-8
import sys
print sys.getdefaultencoding ()  



#万能方法
#!/usr/bin/env python 
#coding =utf-8 
string4= "Hello" 
if Isinstance (String4, Unicode): 
  print S.encode (' gb2312 ') 
else: 
  print s.decode (' utf-8 '). Encode (' gb2312 ')



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.