Python Chinese string encoding problem

Source: Internet
Author: User

Interface test, the discovery interface return content is Uncodie type but contains Chinese. Output prompt error when printing with print:

Unicodeencodeerror: ' ASCII ' codec can ' t encode characters in position 733-738:ordinal not in range (128)

Lookup data discovery is due to the inclusion of Chinese characters in the content, which causes the UNIX system to parse in print is not resolved properly.

The source code is as follows:

 def   _ejson (con): Comm  =  " echo '%s ' | python-m json.tool  "  % con  return   Os.system (comm)  if  __name__  = =  "  __main__   : Con  =open ( '  con.json   ' ,  

Access to information and self-examination

found that con returned a Unicode-encoded string in which the Chinese is shifting. Parsing failed when print was caused.

The changed code is as follows:

def_ejson (con): Con= Con.encode ('Utf-8 ') Comm="echo '%s ' | python-m json.tool"%ConreturnOs.system (Comm)if __name__=="__main__": Con=open ('Con.json','R')    Print_ejson (Con)

The problem has been solved perfectly.

With a simple Python coding problem:

Python has two types of strings, str and Unicode:

Because Python considers 16-bit Unicode to be the only inner code of a character, the commonly used character set such as Gb2312,gb18030/gbk,utf-8, and ASCII are binary (byte) encoded forms of characters.

If you need to convert non-Unicode encoded STR to Unicode encoding, you need to use decode for decoding, and if you want to convert the Unicode encoding to a different character set, you need to encode it using encode.

For example: Str.decode (' utf-8 ') converts STR to Unicode encoding

Str.encode (' utf-8 ') converts STR to UTF-8 encoding

In general, we need to convert from Unicode encoding to conversion between different types of encoding.

For example: Str.decode (' GBK '). Encode (' Utf-8 ') turns str from GBK encoding to UTF-8 encoding



Python Chinese string encoding problem

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.