【python】 全角半角转换

时间:2021-11-12 17:51:04

以输入为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;