python实现全角半角的相互转换

2022-10-22,,,,

转换说明

 

全角半角转换说明

全角字符unicode编码从65281~65374 (十六进制 0xff01 ~ 0xff5e)

半角字符unicode编码从33~126 (十六进制 0x21~ 0x7e)

空格比较特殊,全角为 12288(0x3000),半角为 32(0x20)

 

除空格外,全角/半角按unicode编码排序在顺序上是对应的(半角 + 0x7e= 全角),所以可以直接通过用+-法来处理非空格数据,对空格单独处理。

 

 

 

参考代码

 

复制代码

# -*- coding: cp936 -*-

def strq2b(ustring):

    """把字符串全角转半角"""

    rstring = ""

    for uchar in ustring:

        inside_code=ord(uchar)

        if inside_code >= 0x0021 and inside_code <= 0x7e:   #全角直接返回

            rstring += uchar

        else:

            if inside_code==0x3000:                         #全角角空格单独处理 

                inside_code = 0x0020

            else:                                           #其他的全角半角的公式为:半角 = 全角- 0xfee0

                inside_code -= 0xfee0

            

            rstring += chr(inside_code)          

    return rstring

 

def strb2q(ustring):

    """把字符串半角转全角"""

    rstring = ""

    for uchar in ustring:

        inside_code=ord(uchar)

        if inside_code < 0x0020 or inside_code > 0x7e:   #全角直接返回

            rstring += uchar

        else:

            if inside_code==0x0020:                         #半角空格单独处理 

                inside_code = 0x3000

            else:                                           #其他的全角半角的公式为:全角 = 半角+0xfee0

                inside_code += 0xfee0

            

            rstring += unichr(inside_code)           

    return rstring

 

 

###测试

b = strb2q("mn123abc".decode('cp936'))                           

print b

 

c = strq2b("mn123abc".decode('cp936'))

print c

 

 

 

 

 

库函数说明

 

chr()函数用一个范围在range(256)内的(就是0~255)整数作参数,返回一个对应的字符。

unichr()跟它一样,只不过返回的是unicode字符。

 

ord()函数是chr()函数(对于8位的ascii字符串)或unichr()函数(对于unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ascii数值,或者unicode数值。

《python实现全角半角的相互转换.doc》

下载本文的Word格式文档,以方便收藏与打印。