pyList

python 半角全角的相互转换

半角全角的相互转换,经常用到。

python code: 半角全角的转换

# -*- coding: utf-8 -*-

def strQ2B(ustring):
    """把字符串全角转半角"""
    rstring = ""
    for uchar in ustring:
        inside_code=ord(uchar)
        if inside_code==0x3000:
            inside_code=0x0020
        else:
            inside_code-=0xfee0
        if inside_code0x7e:      #转完之后不是半角字符则返回原来的字符
            rstring += uchar
        rstring += unichr(inside_code)
    return rstring

def strB2Q(ustring):
    """把字符串半角转全角"""
    rstring = ""
    for uchar in ustring:
        inside_code=ord(uchar)
        if inside_code0x7e:      #不是半角字符则返回原来的字符
            rstring += uchar
        if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0
            inside_code=0x3000
        else:
            inside_code+=0xfee0
        rstring += unichr(inside_code)
    return rstring

def b2q(ustr):
        return ''.join(unichr(0x3000 if c == 0x0020 else c+0xfee0 if 0x0020 < c < 0x0080 else c) for c in map(ord, ustr))

def q2b(ustr):
        return ''.join(unichr(0x0020 if c == 0x3000 else c-0xfee0 if 0xff00 < c < 0xff80 else c) for c in map(ord, ustr))

print strB2Q('aoe')
print b2q('aoe')
本文网址: https://pylist.com/t/1380336767 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles