Python中文字符具體應(yīng)用技巧分享
在Python編程語言中有很多比較有用的操作可以幫助我們輕松的實現(xiàn)一些特定環(huán)境下的功能。比如在對中文字符的操作方面等等。今天我們就一起來了解一下有關(guān)Python中文字符的相關(guān)應(yīng)用技巧。
Python中文字符相關(guān)操作代碼示例:
- #!/usr/bin/python
- #-*- coding: utf-8 -*-
- s = "中國"
- ss = u"中國"
- print s, type(s), len(s)
- print ss, type(ss), len(ss)
- print '-' * 40
- print repr(s)
- print repr(ss)
- print '-' * 40
- ss1 = s.decode('utf-8')
- print s1,len(s1),type(s1)
- print '-' * 40
- ss2 = s.decode('utf-8').encode('gbk')
- print s2
- print type(s2)
- print len(s2)
- print '-' * 40
- s3 = ss.encode('gbk')
- print s3
- print type(s3)
- print len(s3)
執(zhí)行結(jié)果如下:
- 中國 < type 'str'> 6
- 中國 < type 'unicode'> 2
- ----------------------------------------
- '\xe4\xb8\xad\xe5\x9b\xbd'
- u'\u4e2d\u56fd'
- ----------------------------------------
- 中國 2 < type 'unicode'>
- ----------------------------------------
- �й
- < type 'str'>
- 4
- ----------------------------------------
- �й
- < type 'str'>
- 4
補充:
查看Python中文字符中默認編碼設(shè)置:
- >>> import sys
- >>> sys.getdefaultencoding()
- 'ascii'
由于在文件的頭上已經(jīng)指明了#-*- coding: utf-8 -*- ,則s的編碼已是utf-8。#t#
在utf-8下,英文字母占一個字節(jié),中文占3個字節(jié);
unicode下的中文是1個字符(雙字節(jié));
GBK編碼下的中文占2個字節(jié)。(感謝keakon的指正)
以上就是對Python中文字符的相關(guān)介紹。