Windows下Python字串編碼問題

來源:互聯網
上載者:User

標籤:

Python語言實際上有三種字串,通常意義的字串(str),Unicode字串(unicode)和抽象類別basestring,其中basestring不可執行個體化。
在Windows系統下的CPython解譯器輸入代碼:

>>> st1 = ‘中文‘>>> st1‘\xd6\xd0\xce\xc4‘>>> type(st1)<type ‘str‘>>>> st2 = st1.decode(‘gbk‘)>>> st2u‘\u4e2d\u6587‘>>> type(st2)<type ‘unicode‘>>>> st3 = st2.encode(‘utf-8‘)>>> st3‘\xe4\xb8\xad\xe6\x96\x87‘>>> type(st3)<type ‘str‘>>>> st4 = st2.encode(‘gbk‘)>>> st4‘\xd6\xd0\xce\xc4‘>>> type(st4)<type ‘str‘>

如果在代碼中加入一句:

>>> st5 = st1.decode(‘utf-8‘)

則會報錯

從上面的代碼和輸出我們可以得到如下結論:
1、Windows命令列輸入的預設中文編碼格式是gbk,輸入的中文字串類型為str
2、使用decode函數可以將一個str類型的中文字串轉成unicode類型
3、使用encode函數可以將一個unicode類型的中文字串轉成str類型

所以我們一般在進行Python指令碼編寫的時候,需要在指令碼的開頭加上如下代碼:

#-*- coding:utf-8 -*-

也可以匯入模組sys,設定預設編碼格式:

import syssys.setdefaultencoding(‘utf-8‘)

PS: Python版本為python2.7

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Windows下Python字串編碼問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.