# coding=utf-8
def str_Q2B(u_string):
"""
全角转半角
全角字符unicode编码从65281~65374 (十六进制 0xFF01 ~ 0xFF5E)
半角字符unicode编码从33~126 (十六进制 0x21~ 0x7E)
空格比较特殊,全角为 12288(0x3000),半角为 32(0x20)
除空格外,全角/半角按unicode编码排序在顺序上是对应的(半角 + 0x7e= 全角),
所以可以直接通过用+-法来处理非空格数据,对空格单独处理。
"""
r_string = ""
for uchar in u_string:
inside_code = ord(uchar)
if inside_code == 0x3000: # 全角空格直接转换
inside_code = 0x0020
else:
inside_code -= 0xfee0
if inside_code < 0x0020 or inside_code > 0x7e:
r_string += uchar
r_string += unichr(inside_code)
return r_string
def str_B2Q(u_string):
"""
半角转全角
"""
r_string = ""
for uchar in u_string:
inside_code = ord(uchar)
if inside_code < 0x0020 or inside_code > 0x7e: # 不是半角字符就返回原来的字符
r_string += uchar
if inside_code == 0x0020: # 除了空格其他的全角半角的公式为:半角=全角-0xfee0
inside_code = 0x3000
else:
inside_code += 0xfee0
r_string += unichr(inside_code)
return r_string
a = str_B2Q("abc12345")
print a
b = str_Q2B(a)
print b
全角转半角/半角转全角(Python)
最新推荐文章于 2023-01-31 22:16:50 发布