Convert Python print encoding to default encoding

Source: Internet
Author: User

Python print encoding has many application scopes. Here we will first look at how to convert the default encoding into system encoding. I hope you will have some gains. When encode is used and decode is used, it is always confused at the beginning.

In fact, the English name of various local Character sets is Coded Character Set. to convert it to Coded, it must be an encode. Similarly, it should also be called decode ......

Decode converts other encodings to unicode, which is equivalent to unicode functions. encode converts unicode encoded strings to specific encodings. Continue In pyshell:

A is of the Str type, so an error is returned when you use encode. When print is used, will the default encoding be called to convert to system encoding?

Python print Encoding

 
 
  1. >>> a.decode("gb2312")   
  2. u'\u6211'   
  3. >>> print a.decode("gb2312")   
  4. >>> a.encode("gb2312")   
  5. Traceback (most recent call last):   
  6. File "<input>", line 1, in ?   
  7. UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in 
    position 0: ordinal not in range(128)   

B is of the unicode type. During printing, encode must be encoded into the system encoding.

Python code

 
 
  1. >>> print b.encode("gb2312")   
  2. >>> b.encode("gb2312")   
  3. '\xce\xd2'   
  4. >>> b.decode("gb2312")   
  5. Traceback (most recent call last):   
  6. File "<input>", line 1, in ?   
  7. UnicodeEncodeError: 'ascii' codec can't encode character 
    u'\u6211' in position 0: ordinal not in range(128)  

The default encode and decode in Python print encoding are in strict mode, so an Error is thrown directly, while the default replace mode is in Java, therefore, when processing Servlets, we often see a string ????? When decode is passed in, the second parameter errors is set to 'replace ', which can be the same as Java, but it is always unsuccessful and I don't know why.

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.