全形轉半形 半形轉全形(Python)

2021-07-16 08:24:31 字數 1180 閱讀 5291

# coding=utf-8

def str_q2b(u_string):

"""全形轉半形

全形字符unicode編碼從65281~65374 (十六進製制 0xff01 ~ 0xff5e)

半形字元unicode編碼從33~126 (十六進製制 0x21~ 0x7e)

空格比較特殊,全形為 12288(0x3000),半形為 32(0x20)

除空格外,全形/半形按unicode編碼排序在順序上是對應的(半形 + 0x7e= 全形),

所以可以直接通過用+-法來處理非空格資料,對空格單獨處理。

"""r_string = ""

for uchar in u_string:

inside_code = ord(uchar)

if inside_code == 0x3000: # 全形空格直接轉換

inside_code = 0x0020

else:

inside_code -= 0xfee0

if inside_code < 0x0020 or inside_code > 0x7e:

r_string += uchar

r_string += unichr(inside_code)

return r_string

def str_b2q(u_string):

"""半形轉全形

"""r_string = ""

for uchar in u_string:

inside_code = ord(uchar)

if inside_code < 0x0020 or inside_code > 0x7e: # 不是半形字元就返回原來的字元

r_string += uchar

if inside_code == 0x0020: # 除了空格其他的全形半形的公式為:半形=全形-0xfee0

inside_code = 0x3000

else:

inside_code += 0xfee0

r_string += unichr(inside_code)

return r_string

a = str_b2q("abc12345")

print a

b = str_q2b(a)

print b

全形轉半形與半形轉全形

1.全形 指乙個字元占用兩個標準字元位置。漢字字元和規定了全形的英文本元及國標gb2312 80中的圖形符號和特殊字元都是全形字符。一般的系統命令是不用全形字符的,只是在作文書處理時才會使用全形字符。2.半形 指一字元占用乙個標準的字元位置。通常的英文本母 數字鍵 符號鍵都是半形的,半形的顯示內碼都...

全形轉半形

轉半形的函式 dbc case 全形空格為12288,半形空格為32 其他字元半形 33 126 與全形 65281 65374 的對應關係是 均相差65248 param input 任意字串 return 半形字串 public static string todbc string input ...

全形轉半形函式 全形數字轉半形數字

private static char doublebytetohalfangle char c byte bs system.text.encoding.unicode.getbytes cs,0,1 if bs.length 2 return cs 0 private static string...