您的位置:首页 > 编程语言 > Python开发

python--汉字字符处理

2017-06-24 16:08 155 查看
一、输出一串汉字字符串

#-*—coding:utf8-*-
def txt_test():
string = u'今天你有毒!'
print string

txt_test()


输出:



二、输出字符串长度

#-*—coding:utf8-*-
def txt_test():
string = '今天你有毒!'
print string
print len(string)

txt_test()


输出: 18–与汉字的长度不符。



三、解码成UTF-8格式并测量长度

方法一:

#-*—coding:utf8-*-
def txt_test():
string = u'今天你有毒!'
print string
print len(string)

txt_test()


方法二:

#-*—coding:utf8-*-
def txt_test():
string = '今天你有毒!'
print string
print len(string)
print len(string.decode('utf-8'))

txt_test()


输出:6–和汉字实际的长度一致。



四、把汉字字符串一个汉字一个汉字的输出

方法一:

#-*—coding:utf8-*-
def txt_test():
string = u'今天你有毒!'
print string
print len(string)
print len(string)
for i in range(0,len(string),1):
print string[i]

txt_test()


输出:



方法二:

#-*—coding:utf8-*-
def txt_test():
string = '今天你有毒!'
print string
print len(string)
print len(string.decode('utf-8'))
for i in range(0,len(string.decode('utf-8')),1):
print string.decode('utf-8')[i]

txt_test()


输出:



方法二:

五、判断汉字字符串里面是否有某个汉字

方法一:

#-*—coding:utf8-*-
def txt_test():
string = u'今天你有毒!'
print string
print len(string)
print len(string)
for i in range(0,len(string),1):
print string[i]
if string[i] == u'毒':
print u'这句话里有个毒'

txt_test()




方法二:

#-*—coding:utf8-*-
def txt_test():
string = '今天你有毒!'
print string
print len(string)
print len(string.decode('utf-8'))
for i in range(0,len(string.decode('utf-8')),1):
print string.decode('utf-8')[i]
if string.decode('utf-8')[i] == u'毒':
print '这句话里有个毒'

txt_test()


输出:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: