python支援中文

來源:互聯網
上載者:User

環境:python 2.7.*

做法:

在.py檔案中,要加

# -*- coding:utf-9 -*-

如果要支援中文,必須在中文前面加u,如u‘我是pythoner’


解釋:
>>> test1 = "我是pythoner"

>>> test2 = u"我是pythoner"

>>> test1
'\xe6\x88\x91\xe6\x98\xafpythoner'
>>> test2
u'\u6211\u662fpythoner'


>>> test11 = test1.encode('gb2312')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
>>> test12 = test1.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
>>> test13 = test1.decode('utf-8')
>>> test13
u'\u6211\u662fpythoner'
>>> test14 = test1.decode('gb2312')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 0-1: illegal multibyte sequence

>>> test15 = test1.decode('utf-8').encode('utf-8')
>>> test15
'\xe6\x88\x91\xe6\x98\xafpythoner'
>>> test16 = test1.decode('utf-8').encode('gb2312')
>>> test16
'\xce\xd2\xca\xc7pythoner'

>>> test21 = test2.encode('gb2312')
>>> test21
'\xce\xd2\xca\xc7pythoner'
>>> test22 = test21.decode('gb2312')
>>> test22
u'\u6211\u662fpythoner'
>>> test23 = test2.encode('gb18030')
>>> test23
'\xce\xd2\xca\xc7pythoner'
>>> test24 = test23.decode('gb2312')
>>> test24
u'\u6211\u662fpythoner'

>>> test25 = test23.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)


結論:

        本來是gb2312碼,只能解碼為utf-8 ,後編碼為gb18030碼

        本來是utf-8碼,編碼為其他碼,解碼的時候,也要為相應的碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.