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

创新互联专注于浮梁网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供浮梁营销型网站建设,浮梁网站制作、浮梁网页设计、浮梁网站官网定制、小程序开发服务,打造浮梁网络公司原创品牌,更为您提供浮梁网站排名全网营销落地服务。
Python中文字符相关操作代码示例:
- #!/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)
 
执行结果如下:
- 中国 < 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中文字符中默认编码设置:
- >>> import sys
 - >>> sys.getdefaultencoding()
 - 'ascii'
 
由于在文件的头上已经指明了#-*- coding: utf-8 -*- ,则s的编码已是utf-8。#t#
在utf-8下,英文字母占一个字节,中文占3个字节;
unicode下的中文是1个字符(双字节);
GBK编码下的中文占2个字节。(感谢keakon的指正)
以上就是对Python中文字符的相关介绍。
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号