自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python中文字符具體應(yīng)用技巧分享

開發(fā) 后端
Python中文字符的相關(guān)代碼操作方法將會在這篇文章中詳細介紹,希望大家可以以此為參考對象,從而熟練的掌握這一應(yīng)用技術(shù)。

Python編程語言中有很多比較有用的操作可以幫助我們輕松的實現(xiàn)一些特定環(huán)境下的功能。比如在對中文字符的操作方面等等。今天我們就一起來了解一下有關(guān)Python中文字符的相關(guān)應(yīng)用技巧。

Python中文字符相關(guān)操作代碼示例:

  1. #!/usr/bin/python  
  2. #-*- coding: utf-8 -*-  
  3. s = "中國" 
  4. ss = u"中國" 
  5. print s, type(s), len(s)  
  6. print ss, type(ss), len(ss)  
  7. print '-' * 40  
  8. print repr(s)  
  9. print repr(ss)  
  10. print '-' * 40  
  11. ss1 = s.decode('utf-8')  
  12. print s1,len(s1),type(s1)  
  13. print '-' * 40  
  14. ss2 = s.decode('utf-8').encode('gbk')  
  15. print s2  
  16. print type(s2)  
  17. print len(s2)  
  18. print '-' * 40  
  19. s3 = ss.encode('gbk')  
  20. print s3  
  21. print type(s3)  
  22. print len(s3) 

 

執(zhí)行結(jié)果如下:

 

  1. 中國 < type 'str'> 6  
  2. 中國 < type 'unicode'> 2  
  3. ----------------------------------------  
  4. '\xe4\xb8\xad\xe5\x9b\xbd'  
  5. u'\u4e2d\u56fd'  
  6. ----------------------------------------  
  7. 中國 2 < type 'unicode'> 
  8. ----------------------------------------  
  9. �й  
  10. < type 'str'> 
  11. 4  
  12. ----------------------------------------  
  13. �й  
  14. < type 'str'> 

 

補充:

查看Python中文字符中默認編碼設(shè)置:

  1. >>> import sys  
  2. >>> sys.getdefaultencoding()  
  3. '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)介紹。

責(zé)任編輯:曹凱 來源: 博客園
相關(guān)推薦

2010-02-02 16:49:32

C++中文字符

2009-11-26 16:43:11

PHP截取中文字符串

2009-11-27 09:55:11

PHP截取中文字符

2010-09-01 14:20:19

CSS排版

2009-11-26 16:26:32

PHP字符串mbstr

2011-06-16 17:01:21

Qt MeeGo 排序

2010-02-25 15:25:19

WCF通道

2010-02-23 13:03:34

WCF序列化

2010-03-03 16:25:41

Python字符串顯示

2024-03-11 06:05:00

C++字符串

2010-01-13 16:45:44

VB.NET刪除控件

2010-02-24 17:07:26

WCF序列化引擎

2009-12-03 10:09:36

linux添加字體中文字體

2010-03-03 16:57:28

Python字符

2009-12-01 15:41:16

PHP substr截

2010-02-03 15:35:00

C++輸入輸出漢字

2011-01-11 10:05:29

Linux中文字體

2021-04-13 14:36:00

鴻蒙HarmonyOS應(yīng)用

2009-12-15 10:23:23

Ruby應(yīng)用技巧

2009-11-25 17:28:26

PHP對話
點贊
收藏

51CTO技術(shù)棧公眾號