This example describes the Python encoding type conversion method. Share to everyone for your reference, as follows:
1:python and Unicode
To correctly handle multilingual text, Python introduced a Unicode string after version 2.0.
Print in the 2:python
While Python internally needs to convert the text encoding to Unicode encoding, the terminal display work is done by a traditional Python string (in fact, Python's print statement cannot print a double-byte Unicode encoded character at all).
Python's print will automatically encode the output's Unicode encoding (for other non-Unicode encodings, print as-is output), and the Write method of the file object does not do so when some strings are output normally with print, Write to file is not necessarily the same as print.
Under Linux, it is converted according to environment variables, which can be seen using the locale command under Linux. Print statement its implementation is to send the output of the content of the operating system, the operating system according to the system encoding the input byte stream encoding.
>>>str= ' learn python ' >>> str ' \xe5\xad\xa6\xe4\xb9\xa0python ' #asII编码 >>> print str Learn python >>> str=u ' learn python ' >>> str # # # #unicode编码 ' \xe5u\xad\xa6\xe4\xb9\xa0python '
The Decode in 3:python
Convert other character sets to Unicode encoding (only Chinese characters need to be converted)
>>> str= ' learning ' >>> ustr=str.decode (' utf-8 ') >>> ustru ' \u5b66\u4e60 '
In this way, the Chinese characters are encoded and converted, and Python can be used for subsequent processing; (If you do not convert, Python will make the default encoding conversion based on the machine's environment variables, which may cause garbled characters)
The Encode in 4:python
Convert Unicode to another character set
>>> str= ' learning ' >>> ustr=str.decode (' utf-8 ') >>> ustru ' \u5b66\u4e60 ' >>> ustr.encode (' Utf-8 ') ' \xe5\xad\xa6\xe4\xb9\xa0 ' >>> print ustr.encode (' utf-8 ') learning