如何通过python转换全角字符串为半角字符串

# coding:utf-8

from idna import unichr

def all_to_half(all_string):
    """全角转半角"""
    half_string = ""
    for char in all_string:
        inside_code = ord(char)
        if inside_code == 12288:  # 全角空格直接转换,全角和半角的空格的Unicode值相差12256
            inside_code = 32
        elif (inside_code >= 65281 and inside_code <= 65374):  # 全角字符(除空格)根据关系转化,除空格外的全角和半角的Unicode值相差65248
            inside_code -= 65248

        half_string += unichr(inside_code)
    return half_string

 

posted @ 2021-12-23 20:25  eliwang  阅读(469)  评论(0编辑  收藏  举报