Python Encoding type conversion

Source: Internet
Author: User
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

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.