Python Coding Summary:
1). First Python has two forms of string, str and Unicode, where Unicode is equivalent to bytecode, which can be used across platforms.
Str converted to Unicode can be u,str.decode in three ways by Unicode ()
Unicode is converted to STR, and if it is in Chinese, it is generally encode by the way
2). If there is Chinese in the code, we will generally add "# Coding=utf-8", what is the role of this, generally as follows:
- This declaration is required if there is a Chinese comment in the code
- A more advanced editor, such as my Emacs, will format this as a code file based on the header declaration.
- The program will initialize the "Life is too short" by the head Declaration, decoding the Unicode object, (so the header declaration and the code are stored in the same format
So, when we fill in the code header, use s= "Chinese", actually type (s) is a str, is already encoding Unicode in utf-8 format into str.
Second, if we use s=u ' Chinese ' in our code, it is equivalent to decoding str in utf-8 to Unicode.
1 #Coding=utf-82 __author__='Lenovo'3 4A='English'5 PrintA,type (a)6 7A2=unicode (A,"Utf-8")8 PrintA2,type (A2)9 TenA3=u'English' One PrintA3,type (A3)
The output is as follows, stating that the function of the declaration header is to automatically convert the Unicode to Utf-8, and the other is to specify the utf-8 when using U:
3) If Unicode is above Unicode, it does not actually play an effect.
1 a=' Chinese '2 a2=unicode (A,"utf-8") 3 Print A2,type (A2) 4 5 a3=Unicode (A2)6print a3,type (A3)
4) U,unicode () and Str.decode equivalent, can convert STR to Unicode. But decode cannot be called consecutively like Unicode ()
1 a=' Chinese '2 a2=unicode (A,"utf-8") 3 A3=a.decode ("utf-8")4print A2, Type (A2)5print a3,type (A3)
5) When the key stored in the map is Chinese, str can be converted to Unicode, so that it can cross the platform
1A='English'2map={}3Map[a.decode ('Utf-8')]=34Map[unicode ('T')]=45 PrintMap6 PrintMap[u'English']7 Printmap['T']
6) The last point to note is the ASCII code, Unicode and STR equivalent, that is, Unicode (' t ') = = ' t '
Python encoding format