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