Python2 and Python3 Codes

Source: Internet
Author: User

Python2 encoding

Unicode:unicode Hello u ' \u4f60\u597d '
| | | |
Encode (' UTF8 ') | |decode (' UTF8 ') encode (' GBK ') | |decode (' GBK ')
| | | |
UTF8 GBK
Encoded STR ' \XE4\XBD\XA0\XE5\XA5\XBD ' encoded GBK u ' \U6D63\U72B2\U30BD '


# str:bytes

' Hello World ' Print repr (s) ' \xe4\xbd\xa0\xe5\xa5\xbd World ' Print Len (s) Print type (s) ' Str '>

# Unicode:unicode

>>> s = u' Hello World'print  repr (s) u'\u4f60\u597d World'printprint  type (s)'Unicode '>

#unicode: No matter what character has a counterpart in Unicode.

Features of Python2
1. In Python2, print bytes are converted to Unicode

2.python2 in the default ASCII encoding
[email protected] ~]# cat python.py
#coding: UTF8 # tells the interpreter to encode UTF8
print ' Hello '

Python3 encoding
UTF8 encoded by default in Python3

Str:unicode Hello u ' \u4f60\u597d '
| | | |
Encode (' UTF8 ') | |decode (' UTF8 ') encode (' GBK ') | |decode (' GBK ')
| | | |
UTF8 GBK
Encoded STR ' \XE4\XBD\XA0\XE5\XA5\XBD ' encoded GBK u ' \U6D63\U72B2\U30BD '

' Hello World ' Print (Json.dumps (s)) " \u4f60\u597d World " Print (Len (s)) Print (type (s))<class'str'>

Encoding and decoding mode 1:

>>> s ='Hello World'>>> B = S.encode ('UTF8')>>>Print(b) B'\xe4\xbd\xa0\xe5\xa5\xbd World'>>> s = B.decode ('UTF8')>>>Print(s) Hello world>>> s = B.decode ('GBK')>>>Print(s) raccoon à ソworld

Encoding and decoding mode 2:

>>> s ='Hello World'>>> B = bytes (S,'GBK')>>>Print(b) B'\xc4\xe3\xba\xc3 World'>>> s = str (b,'GBK')>>>Print(s) Hello world>>> s ='Hello World'>>> B = bytes (S,'UTF8') >>>Print(b) B'\xe4\xbd\xa0\xe5\xa5\xbd World'>>> s = str (b,'UTF8')>>>Print(s) Hello world>>> s = str (b,'GBK') >>>Print(s) raccoon à ソworld

Python2 and Python3 Codes

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.