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

开发 后端
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。#t#
 

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

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

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

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

责任编辑:曹凯 来源: 博客园
相关推荐

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-03-03 16:25:41

Python字符串显示

2024-03-11 06:05:00

C++字符串

2010-02-23 13:03:34

WCF序列化

2009-12-03 10:09:36

linux添加字体中文字体

2009-12-01 15:41:16

PHP substr截

2010-03-03 16:57:28

Python字符

2010-02-24 17:07:26

WCF序列化引擎

2010-01-13 16:45:44

VB.NET删除控件

2021-04-13 14:36:00

鸿蒙HarmonyOS应用

2011-01-11 10:05:29

Linux中文字体

2010-02-03 15:35:00

C++输入输出汉字

2009-12-15 10:23:23

Ruby应用技巧

2010-02-04 09:37:31

点赞
收藏

51CTO技术栈公众号