zoukankan      html  css  js  c++  java
  • python实现字符串中的半全角转换

    • 全角和半角的空格的Unicode值相差12256
    • 除空格外的全角和半角的Unicode值相差65248
    # -*- 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
  • 相关阅读:
    高阶函数
    如何理解data URL?
    JS对象的创建方式
    数组中的map方法
    奇怪的 Javascript
    什么场景不适合箭头函数
    协方差矩阵学习[转载]
    PAT 1140 Look-and-say Sequence [比较]
    PAT 1089 Insert or Merge[难]
    PAT 1096 Consecutive Factors[难]
  • 原文地址:https://www.cnblogs.com/Micang/p/9769921.html
Copyright © 2011-2022 走看看