The method of realizing full-angle half-angle conversion in Python _python

Source: Internet
Author: User
Tags ord ustring in python

This article illustrates Python's method of realizing full-width half angle conversion, and believes that Python learning can be used for reference. As shown below:

First, full-angle half-angle Conversion Overview:

Full-width character Unicode encoding from 65281~65374 (hexadecimal 0xff01 ~ 0xff5e)
Half-width character Unicode encoding from 33~126 (hexadecimal 0x21~ 0x7E)
The space is more special, the whole angle is 12288 (0x3000), half angle is (0x20)
In addition, all corners/half-width are sorted in the order of Unicode encoding.
So we can deal with the blank data directly by using the +-method.

Two, full angle turn half angle:

The implementation code is as follows:

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

Three, half angle to turn the whole angle:

The implementation code is as follows:

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 : #除了空格其他的全角半角的公式为: half-width = full-width -0xfee0
      inside_code=0x3000
    else:
      inside_code+=0xfee0
    rstring + = UNICHR (Inside_code)
  Return rstring

Four, test code:

A = strb2q ("abc12345")
print a
b = strq2b (a)
print B

Output:

abc12345
abc12345

Interested friends can debug run a bit, I believe there will be a certain harvest.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.