或者為pycharm設置代碼模版,這樣每次新建Python文件時會自動帶上以上代碼。如果不添加,即使中文字符串以u開頭,也是編譯不通過的。
如果不帶u的字符在包含了# coding: utf-8的腳本中默認字符為UTF-8,一般也不會有什么問題。
UNICODE轉GBK:# 帶u的字符串為unicodes.encode('gbk')UNICODE轉UTF-8# 帶u的字符串為unicodes.encode('utf-8')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編碼,轉換字符 passelse: pass或:
s.decode('utf-8', 'ignore')新聞熱點
疑難解答