代码改变世界

python 截取指定长度汉字

2013-08-01 13:35  江湖么名  阅读(586)  评论(0编辑  收藏  举报

这个方法不是很好,不知道有没有更好的方法

def cut_hz(s, length):
    charstyle = chardet.detect(s)
    t = s[:length]
    try:
        unicode(t, charstyle['encoding'])
    except:
        t = s[:length-1]
    return t

 

这样更好一点

def cut_hz(s, length):
    charstyle = chardet.detect(s)
    uni_s = unicode(s, charstyle['encoding'])
    return uni_s[0:length]