Python实现全角半角转换的方法

yipeiwu_com5年前Python基础

本文实例讲解了Python实现全角半角转换的方法,相信对于大家的Python学习能够起到一定的参考借鉴价值。如下所示:

一、全角半角转换概述:

全角字符unicode编码从65281~65374 (十六进制 0xFF01 ~ 0xFF5E)
半角字符unicode编码从33~126 (十六进制 0x21~ 0x7E)
空格比较特殊,全角为 12288(0x3000),半角为 32 (0x20)
而且除空格外,全角/半角按unicode编码排序在顺序上是对应的
所以可以直接通过用+-法来处理非空格数据,对空格单独处理

二、全角转半角:

实现代码如下:

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_code<0x0020 or inside_code>0x7e:   #转完之后不是半角字符返回原来的字符
      rstring += uchar
    rstring += unichr(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
    if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0
      inside_code=0x3000
    else:
      inside_code+=0xfee0
    rstring += unichr(inside_code)
  return rstring

四、测试代码:

a = strB2Q("abc12345")
print a
b = strQ2B(a)
print b

输出:

abc12345
abc12345

感兴趣的朋友可以调试运行一下,相信会有一定的收获。

相关文章

使用python分析git log日志示例

用git来管理工程的开发,git log是非常有用的‘历史'资料,需求就是来自这里,我们希望能对git log有一个定制性强的过滤。此段脚本就是在完成这种类型的任务。对于一个repo所有...

解决在pycharm中显示额外的 figure 窗口问题

解决在pycharm中显示额外的 figure 窗口问题

问题描述 在电脑中重新安装Anaconda3&PyCharm后,运行原来的程序画图时出现了下图界面。 不能弹出如下图所示的“figure”窗口。 解决方法: 这是因为PyCharm在...

Python操作MongoDB数据库PyMongo库使用方法

引用PyMongo 复制代码 代码如下: >>> import pymongo 创建连接Connection 复制代码 代码如下: >>> impo...

django框架创建应用操作示例

本文实例讲述了django框架创建应用操作。分享给大家供大家参考,具体如下: 18.1.5  安装Django 安装Django node2:/root#pip insta...

tornado+celery的简单使用详解

celery是实现一个简单,灵活可靠的分布式任务队列系统的好选择 tornado则不用过多介绍 在开发机上安装rabbitmq这里就不介绍了 首先是task文件的编写 task.py...