亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實(shí)現(xiàn)全角半角轉(zhuǎn)換的方法

 更新時(shí)間:2014年08月18日 15:04:26   投稿:shichen2014  
這篇文章主要介紹了Python實(shí)現(xiàn)全角半角轉(zhuǎn)換的方法,很實(shí)用的方法,需要的朋友可以參考下

本文實(shí)例講解了Python實(shí)現(xiàn)全角半角轉(zhuǎn)換的方法,相信對(duì)于大家的Python學(xué)習(xí)能夠起到一定的參考借鑒價(jià)值。如下所示:

一、全角半角轉(zhuǎn)換概述:

全角字符unicode編碼從65281~65374 (十六進(jìn)制 0xFF01 ~ 0xFF5E)
半角字符unicode編碼從33~126 (十六進(jìn)制 0x21~ 0x7E)
空格比較特殊,全角為 12288(0x3000),半角為 32 (0x20)
而且除空格外,全角/半角按unicode編碼排序在順序上是對(duì)應(yīng)的
所以可以直接通過用+-法來處理非空格數(shù)據(jù),對(duì)空格單獨(dú)處理

二、全角轉(zhuǎn)半角:

實(shí)現(xiàn)代碼如下:

def strQ2B(ustring):
  """把字符串全角轉(zhuǎn)半角"""
  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:   #轉(zhuǎn)完之后不是半角字符返回原來的字符
      rstring += uchar
    rstring += unichr(inside_code)
  return rstring

三、半角轉(zhuǎn)全角:

實(shí)現(xiàn)代碼如下:

def strB2Q(ustring):
  """把字符串半角轉(zhuǎn)全角"""
  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

四、測(cè)試代碼:

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

輸出:

abc12345
abc12345

感興趣的朋友可以調(diào)試運(yùn)行一下,相信會(huì)有一定的收獲。

相關(guān)文章

最新評(píng)論