Django 截取中英文混合字符串

在列表显示的时候,我们常常要截取文章标题的长度,Python截取字符串,本来很简单的,但是中文和英文的宽度不一样,在页面看起来长度就差很远了:

length7
这是中文长度七

粗略来算(是粗略哦),一个中文字符的宽度大概等于两个英文字符的宽度。

一个中文字符的utf8编码长度为3,gbk为2

image

所以将使用gbk来计算长度(因为一个中文字符的宽度大概为两个英文字符)

 

@register.filter
def cut_str(str, length=10):
    """
    截取字符串,使得字符串长度等于length,并在字符串后加上省略号
    """
    is_encode = False
    try:
        str_encode = str.encode('gb18030') #为了中文和英文的长度一致(中文按长度2计算)
        is_encode = True
    except:
        pass
    if is_encode:
        l = length*2
        if l < len(str_encode):
            l = l - 3
            str_encode = str_encode[:l]
            try:
                str = str_encode.decode('gb18030') + '...'
            except:
                str_encode = str_encode[:-1]
                try:
                    str = str_encode.decode('gb18030') + '...'
                except:
                    is_encode = False
    if not is_encode:
        if length < len(str):
            length = length - 2
            return str[:length] + '...'
    return str

注:(1)、这里传入的参数 str 是unicode来的。 (2)、之所以使用'gb18030'编码,是因为'gb18030'比gbk的字符集要广。

posted on 2010-06-23 14:42  Q.Lee.lulu  阅读(4485)  评论(0编辑  收藏  举报