【python】 全角半角转换

以输入为GB18030编码字符串为例:

#把全角字符串转半角
def tobanjiao(string):
        ustring = string.decode('GB18030')
        rstring = ""
        for uchar in ustring:
                inside_code=ord(uchar)  
                if inside_code==0x3000:  
                        inside_code=0x0020  
                else:  
                        inside_code-=0xfee0  

                if inside_code<0x0020 or inside_code>0x7e:
                        rstring += uchar.encode('GB18030')
                else:
                        rstring += unichr(inside_code).encode('GB18030')

        return rstring;

  

posted @ 2013-11-14 12:52  liyuxia713  阅读(570)  评论(0编辑  收藏  举报