當前位置:成語大全網 - 新華字典 - 如何理解python3的unicode,以及全角半角轉換

如何理解python3的unicode,以及全角半角轉換

1. unicode是壹個編碼的standard,表明了字符與數字之間的映射,是可變長的。

2. 映射後的數據如何編碼為字節?這個就是具體的編碼規則:目前最主流的是UTF-8,同樣,它也是變字長的。

python3中的str都是unicode的:“The default encoding for Python source code is UTF-8”

python3中的encode:按照encode()括號中的參數對字符串進行編碼,就是生成bytes。

所以:

In:'中文'.encode('utf-8')

Out:b'\xe4\xb8\xad\xe6\x96\x87'

這裏的b就是Byte,\x表示這個x是被轉義的,意思就是0x。又如:

In: 'abc'.encode('utf-8')

Out: b'abc'

上面的b'a'其實表示的是數字97,b'a'的意思就是字符串'a'的binary數字:

[In]:'abc'.encode('utf-8')[0]

[Out]: 97

同時可以把b'\x'進行解碼,即:

In:b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')

Out:'中文'

除了encode('utf-8')外,用ord可以獲得單個utf-8字符對應的數字:

In [60]: ord('a')

Out[60]: 97

In [61]: ord('a')   #這個是全角的a

Out[61]: 65345

除了decode('utf-8')外,用chr可以獲得數字對應的utf-8字符:

In [62]: chr(97)

Out[62]: 'a'

除了unicode還有別的編碼標準嗎?有啊,比如我國的GBK,別名也叫cp936。

全角和半角之分,是指同樣壹個意義的字符,顯示的大小不同.具體來說,全角和半角的編碼是兩個結果:

In [70]: "mn".encode('utf-8')

Out[70]: b'\xef\xbd\x8d\xef\xbd\x8e

[In]:"mn".encode('utf-8')

[Out]:b'mn'

它們有什麽對應關系呢?(引自這裏)

轉換說明

全角半角轉換說明

有規律(不含空格):

全角字符unicode編碼從65281~65374 (十六進制 0xFF01 ~ 0xFF5E)

半角字符unicode編碼從33~126 (十六進制 0x21~ 0x7E)

特例:

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

除空格外,全角/半角按unicode編碼排序在順序上是對應的(半角 + 0x7e= 全角),所以可以直接通過用+-法來處理非空格數據,對空格單獨處理。

代碼在此基礎上改動壹下(將unichr改為chr即可,適應python3),即:

def strQ2B(ustring):

"""全角轉半角"""

rstring = ""

for uchar in ustring:

inside_code=ord(uchar)

if inside_code == 12288: #全角空格直接轉換

inside_code = 32

elif (inside_code >= 65281 and inside_code <= 65374): #全角字符(除空格)根據關系轉化

inside_code -= 65248

rstring += chr(inside_code)

return rstring

In [69]: strQ2B('妳好python')

Out[69]: '妳好python'