Python learning ~ Unicode encoding

Source: Internet
Author: User

IfCodeThe file must be encoded in UTF-8 format:

1. Write the following comments at the beginning of the file

# Coding = UTF-8

2. Or use the following code

Import sys

Reload sys

SYS. setdefaultencoding ('utf-8 ')

Note: Unicode supports different encoding methods. The most famous one is that the UTF-8 encoding of UTF-8. ASCII characters is exactly the same as that of ASCII encoding.

In additionProgramDo not use the string module. use Unicode () and unichar () functions instead of STR () and CHR () functions.

Generally, for file operations and socket operations, the content needs to be converted to UTF-8 and then converted back after processing.

For example, if a file is written in UTF-8 encoding format, the file can be decoded after being read.

 

# Coding = utf-8def toutf_8 (s): If type (s ). _ name __= = 'unicode ': Return S. encode ('utf-8') else: Return s def tounicode (s): If type (s ). _ name __! = 'Unicode ': Return S. decode ('utf-8') else: Return s codec = 'utf-8' file = 'unicode.txt 'Hello _ out = u "world \ n" bytes_out = toutf_8 (hello_out) F = open (file, "W") F. write (bytes_out) F. close () F = open (file, "R") bytes_in = f. read () F. close () hello_in = tounicode (bytes_in) print hello_in

 

 

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.