Python中文字符具体应用技巧分享


在Python编程语言中有很多比较有用的操作可以帮助我们轻松的实现一些特定环境下的功能。比如在对中文字符的操作方面等等。今天我们就一起来了解一下有关Python中文字符的相关应用技巧。

Python中文字符相关操作代码示例:

  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) 

执行结果如下:

  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中文字符中默认编码设置:

  1. >>> import sys  
  2. >>> sys.getdefaultencoding()  
  3. 'ascii' 

由于在文件的头上已经指明了#-*- coding: utf-8 -*- ,则s的编码已是utf-8。

  • Python文件路径具体操作方法经典讲解
  • Python异常基本处理机制详解
  • Python String类型基本应用情况分析
  • Python流程控制关键字基本内容总结
  • Python连接数据库两种常用方法介绍

 

在utf-8下,英文字母占一个字节,中文占3个字节;

unicode下的中文是1个字符双字节);

GBK编码下的中文占2个字节。(感谢keakon的指正)

以上就是对Python中文字符的相关介绍。

相关内容

    暂无相关文章

评论关闭