一.編碼轉換
通常需要以unicode作爲中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。
1.decode的作用是將其他編碼的字符串轉換成unicode編碼,如str1.decode('gb2312'),表示將gb2312編碼的字符串轉換成unicode編碼。
2.encode的作用是將unicode編碼轉換成其他編碼的字符串,如str2.encode('gb2312'),表示將unicode編碼的字符串轉換成gb2312編碼。
3.encode的時候注意這個編碼,可以解決unicode中文轉換的問題
Codec | Operand type | Purpose |
raw_unicode_escape | Unicode string | Produce a string that is suitable as raw Unicode literal in Python source code |
如:froms=froms.encode('raw_unicode_escape', 'ignore').decode('GB18030', 'ignore')
注意:輸出的時候需要考慮IDE的環境變量,可能會出現亂碼,甚至可能會提示:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)。
二.Python代碼中的編碼定義
1.代碼中字符串的默認編碼與代碼文件本身的編碼一致,如:
s='中文'
如果是在utf8的文件中,該字符串就是utf8編碼
如果是在gb2312的文件中,則其編碼爲gb2312。
這種情況下,要進行編碼轉換,都需要先用decode方法將其轉換成unicode編碼,再使用encode方法將其轉換成其他編碼。
通常,在沒有指定特定的編碼方式時,都是使用的系統默認編碼創建的代碼文件
$ python -c "import sys; print sys.getdefaultencoding()"
ascii
2.如果字符串是這樣定義:
s=u'中文'
則該字符串的編碼就被指定爲unicode了,即python的內部編碼,而與代碼文件本身的編碼無關。
因此,對於這種情況做編碼轉換,只需要直接使用encode方法將其轉換成指定編碼即可。