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'

上述就是小编为大家分享的Python中如何使用中文字符了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。