2022年10月14日 星期五

[Python]中文編碼轉換Unicode

透過python搜尋SSID時, 發現會變成Unicode,所以查了一下編碼跟解碼的方法。

SSID看來編碼方式是utf-8,但其實編碼方式蠻多的,就列出來可以看一下長相。

以下程式碼:

#coding:utf-8

import sys


chStr='中文字En'

print (chStr,type(chStr))

輸出: 

中文字En <class 'str'>

print ('-轉utf8------')

UTF8_chStr=chStr.encode('utf-8')

print (UTF8_chStr,type(UTF8_chStr))

UTF8_chStr_decode=chStr.encode('utf-8').decode('utf-8')

print (UTF8_chStr_decode,type(UTF8_chStr_decode))

輸出: 

-轉utf8------

b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97En' <class 'bytes'>

中文字En <class 'str'>


print ('-轉utf16------')

UTF16_chStr=chStr.encode('utf-16')

print (UTF16_chStr,type(UTF16_chStr))

UTF16_chStr_decode=chStr.encode('utf-16').decode('utf-16')

print (UTF16_chStr_decode,type(UTF16_chStr_decode))

輸出: 

-轉utf16------

b'\xff\xfe-N\x87eW[E\x00n\x00' <class 'bytes'>

中文字En <class 'str'>


print ('-轉gbk------')

gbk_chStr=chStr.encode('gbk')

print (gbk_chStr,type(gbk_chStr))

gbk_chStr_decode=chStr.encode('gbk').decode('gbk')

print (gbk_chStr_decode,type(UTF8_chStr_decode))

輸出: 

-轉gbk------

b'\xd6\xd0\xce\xc4\xd7\xd6En' <class 'bytes'>

中文字En <class 'str'>


print ('-unicode_escape------')

uni_chStr=chStr.encode('unicode_escape')

print (uni_chStr,type(uni_chStr))

uni_chStr_decode=chStr.encode('unicode_escape').decode('unicode_escape')

print (uni_chStr_decode,type(uni_chStr_decode))

輸出: 

-unicode_escape------

b'\\u4e2d\\u6587\\u5b57En' <class 'bytes'>

中文字En <class 'str'>


沒有留言:

張貼留言