Python編碼UNICODE GBK UTF-8字符集轉換的正確姿勢
阿新 • • 發佈:2019-01-09
規範
- 指令碼檔案編碼
由於需要經常性使用到中文字元,因此Python指令碼新建後,請在頭部新增程式碼:
# coding: utf-8
或者為pycharm設定程式碼模版,這樣每次新建Python檔案時會自動帶上以上程式碼。如果不新增,即使中文字串以u開頭,也是編譯不通過的。
UNICODE
- 指令碼中的字元最好使用UNICODE編碼(英文可以不需要,但是中文儘量使用),因為UNICODE編碼是比較好的“中間”字符集,比較容易向GBK和UTF-8轉換。例如:
print u"你好"
如果不帶u的字元在包含了# coding: utf-8的指令碼中預設字元為UTF-8,一般也不會有什麼問題。
- UNICODE轉GBK:
# 帶u的字串為unicode
s.encode('gbk')
- UNICODE轉UTF-8
# 帶u的字串為unicode
s.encode('utf-8')
GBK
- GBK轉UNICODE
Windows下的命令列引數為GBK編碼,因此需要對字串進行轉換,轉換方法有兩種。
方法一:
# Create a new Unicode object from the given encoded string.
# encoding defaults to the current default string encoding.
# errors can be 'strict' , 'replace' or 'ignore' and defaults to 'strict'.
unicode(s, "gbk", "ignore")
方法二:
s.decode('gbk', 'ignore')
跨平臺判斷:
if sys.platform == 'win32':
# win下命令列引數為gbk編碼,轉換字元
pass
else:
pass
UTF-8
- UTF-8轉換為UNICODE
unicode(s, "utf-8", "ignore")
或:
s.decode('utf-8', 'ignore')
彙總整理成函式庫
# win下命令列引數為gbk編碼:star.gbk2unicode(sys.argv[1]) + u'也有'
def gbk2unicode(s):
return s.decode('gbk', 'ignore')
# 指令碼檔案#coding:utf-8時預設不帶u的字串為utf8字串:star.utf82unicode('我')
def utf82unicode(s):
return s.decode('utf-8', 'ignore')
# 帶u的字串為unicode
# star.unicode2gbk(u'\u4e5f\u6709')
# star.unicode2gbk(u'也有')
def unicode2gbk(s):
return s.encode('gbk')
# 帶u的字串為unicode
# star.unicode2utf8(u'\u4e5f\u6709')
# star.unicode2utf8(u'也有')
def unicode2utf8(s):
return s.encode('utf-8')
# win下命令列引數為gbk編碼:star.gbk2utf8(sys.argv[1]) + '也有'
def gbk2utf8(s):
return s.decode('gbk', 'ignore').encode('utf-8')
def utf82gbk(s):
return s.decode('utf-8', 'ignore').encode('gbk')