# -*- coding: utf-8 -*-
def strQ2B(ustring):
"""全角转半角"""
rstring = ""
for uchar in ustring:
inside_code=ord(uchar)
if inside_code == 12288: #全角空格直接转换,全角和半角的空格的Unicode值相差12256
inside_code = 32
elif (inside_code >= 65281 and inside_code <= 65374): #全角字符(除空格)根据关系转化,除空格外的全角和半角的Unicode值相差65248
inside_code -= 65248
rstring += unichr(inside_code)
return rstring
def strB2Q(ustring):
"""半角转全角"""
rstring = ""
for uchar in ustring:
inside_code=ord(uchar)
if inside_code == 32: #半角空格直接转化,全角和半角的空格的Unicode值相差12256
inside_code = 12288
elif inside_code >= 32 and inside_code <= 126: #半角字符(除空格)根据关系转化,除空格外的全角和半角的Unicode值相差65248
inside_code += 65248
rstring += unichr(inside_code)
return rstring
b = strQ2B("mn 123abc全角转半角".decode('utf-8'))
print b
c = strB2Q("mn123abc半角转全角".decode('utf-8'))
print c