python 半角全角的相互转换

全角与半角在中文输入法里经常要接触到,后台在处理用户输入数据时需要对半角全角的相互转换。下面是python 实现的半角全角的相互转换功能。

python 半角全角的相互转换

全角与半角

  • 全角指一个字符占用两个标准字符位置的状态。
  • 半角即一个字符占用一个标准字符的位置。

全角占两个字节,半角占一个字节。半角全角主要是针对标点符号来说的,全角标点占两个字节,半角占一个字节,而不管是半角还是全角,汉字都还是要占两个字节。

半角全角的转换

python code: 半角全角的转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# -*- 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/topic/36.html 转摘请注明来源

Suggested Topics

SAE+python+Tornado+pyTenjin 的完整示例

python 简单易懂,Tornado 高效易学,pyTenjin 轻巧快速,SAE 安全稳定使用门槛低。现在把他们结合在一起做了一个可运行在SAE 上的完整示例。...

在 Ubuntu 16.04.6 LTS 系统上安装 Python 3.6.3

自己的阿里云一个 VPS 用的是系统 Ubuntu 16.04.6 LTS,自带的python版本是 `2.7.12` 与 `3.5.2`,有时候要用到 python `3.6`,又不想卸掉原来版本。下面介绍安装 python 3.6.3 的过程,因为版本较旧,遇到一些坑,这里记录一下。...

python 解析电子书的信息

epub 书是可供人们下载的开放性资源格式的电子图书。epub 文件通常与类似亚马逊Kindle 这样的电子阅读器不兼容。...

Leave a Comment