Python print編碼轉變默認編碼
Python print編碼有很多的應用范圍,在這里我們先來看看如何進行默認編碼轉變成為系統編碼。希望大家有所收獲。什么情況用encode,什么情況又是decode呢,剛開始總是被搞昏。
其實各種本地字符集的英文名是Coded Character Set,要轉換為Coded,肯定是要encode了,同樣,從里面解出來也應該叫decode……
decode就是把其他編碼轉換為unicode,等同于unicode函數;encode就是把unicode編碼的字符串轉換為特定編碼。在pyshell里繼續:
a是Str類型的,所以再用encode會報錯。用print輸出時會調用默認編碼轉換為系統編碼?
Python print編碼
- >>> a.decode("gb2312")
- u'\u6211'
- >>> print a.decode("gb2312")
- >>> a.encode("gb2312")
- Traceback (most recent call last):
- File "<input>", line 1, in ?
- UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in
position 0: ordinal not in range(128)
b是unicode類型,打印時需要先encode(編碼)成系統編碼
Python 代碼
- >>> print b.encode("gb2312")
- >>> b.encode("gb2312")
- '\xce\xd2'
- >>> b.decode("gb2312")
- Traceback (most recent call last):
- File "<input>", line 1, in ?
- UnicodeEncodeError: 'ascii' codec can't encode character
u'\u6211' in position 0: ordinal not in range(128)
Python print編碼里默認的encode和decode是strict模式,所以會直接拋出Error,而Java里是默認replace模式,所以在處理servlet時經常會看到一串?????在decode時傳入第二個參數errors為'replace'可以和Java相同,但總是沒成功,還不知道為什么。
【編輯推薦】