python--汉字字符处理

一、输出一串汉字字符串

#-*—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()

输出:
python--汉字字符处理_第1张图片


方法二:

#-*—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()

输出:

python--汉字字符处理_第2张图片

方法二:

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

方法一:

#-*—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()

python--汉字字符处理_第3张图片


方法二:

#-*—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()

输出:python--汉字字符处理_第4张图片

你可能感兴趣的:(Python)