python符号化処理

1494 ワード

一、pythonにはstrとunicode 1、strの2つの文字列タイプがある:gb 2312、gb 18030/gbk、utf-8、ascii、これらはすべて文字のバイナリ(バイト)符号化形式2、unicode:Pythonは16ビットのunicodeが文字の唯一の内符号3であると考えている.encode:unicodeからバイナリ符号化に変換し、すなわちunicodeからstr 4に変換する.decode:バイナリ符号化からunicode 5に変換し、strとunicodeを同時に含む演算を行う場合、Pythonは一律にstrをunicodeに変換して演算する.もちろん、演算結果もunicodeである.6、提案は
pythonコード
# -*- coding: utf-8 -*-  

#     python   utf-8  

#-----------------------------------------1----------------------------------------
s='   '  #   str    , utf-8   
u=u'   ' #   unicode   

s.decode('utf-8') # str  unicode,  utf-8     s
u.encode('utf-8') # unicode  str,  unicode  utf-8      

s.decode('ascii') #  , ascii  utf-8   
s.decode('gbk')   #   ,     

u.encode('ascii') #  ,     ascii     
u.encode('gbk')   #   ,      

#-----------------------------------------2------------------------------------------
#   :       str unicode    ,Python    str   unicode   ,  ,       unicode。

"  :%s" % s  #   ,         str,     decode  
"  :%s" % u  #   ,     :"  :%s".decode('ascii') % u ,    ascii,  sys.getdefaultencoding()   ascii

import sys
reload(sys)                      # reload      setdefaultencoding     
sys.setdefaultencoding('utf-8')  #    'utf-8',      ,          python      

#  linux $LANG zh_CN.GBK, print s           , print u         ,  u $LANG      

 
参照先:https://in355hz.iteye.com/blog/1860787