在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中文字符的相关介绍。
                标题名称:Python中文字符具体应用技巧分享
                
                文章网址:http://www.csdahua.cn/qtweb/news31/227531.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网