0 初識進制
字符在計算機世界是以0和1表示的,他們有着一一對應的關係,所以我們先從二進制認起
進制 | 一般表示 | Python表示 | 其他/控制檯打印 |
---|---|---|---|
2進制 | 0011 0101 | 0b0011 0101 | |
8進制 | 65 | 0o65 | \065 \65 |
16進制 | 35 | 0x35 | \x35 b'\x35' |
10進制 | 53 | 53 |
ps: 加"\"來轉義常見的那些不能顯示的ASCII字符,同時它已經不是傳統意義上的ASCII字符了,可能只是爲了表示某一進制數
1 常見字符集
通俗的認爲一類字符的集合就是字符集
ASCII字符集: 256個字符
GB2312字符集(簡體字符集)
- GBK字符集(簡繁字符集)
- 通用字符集 (UCS)
- Unicode 字符集
\u5154\u5b50
2 常見字符編碼
字符集與二進制de這類映射關係,我們稱之爲字符編解碼,即若將二進制視爲編碼後的格式,就可認爲字符轉二進制
稱之爲編碼,二進制轉字符
稱之爲解碼
- ASCII 編碼
A -> 65
- ASCII 解碼
65 -> A
- UTF-8 編碼:Unicode 字符集 -> 二進制
\u67ef -> \xe6\x9f\xaf
[解析]柯
對應的Unicode編碼爲\u67ef(0110 0111 1110 1111)
查上表可知柯
需要三個字節,那麼它的組織方式爲:1110 xxxx 10xx xxxx 10xx xxxx
將0110 0111 1110 1111
填充進xx
中即可得到它的二進制表示0110 0111 1110 1111
其16進製表示爲E6 9F AF
,我們打印會發現它是這樣的二進制表示b'\xe6\x9f\xaf'
# 按照utf-8方式編碼
str_tmp = '柯' # 或 str_tmp = '\u67ef'
str_tmp.encode('utf-8')
- UTF-8 解碼
- 所以遇到這樣的字符
\xe6\x9f\xaf
我們想將其轉換爲中文,就需先將其轉化爲Unicode字符,而從二進制轉成Unicode字符,就需要以上的編碼映射關係,這裏我們以UTF-8示例,那麼只需將\xe6\x9f\xaf
解碼即可
\xe6\x9f\xaf-> \u67ef
# 按照utf-8方式解碼
str_tmp = b'\xe6\x9f\xaf'
print(str_tmp.decode('utf-8'))
ps:UTF編碼:Unicode只是字符集,沒有規定編碼,而UTF規定了如何編碼
相關例子彙總[python3]
[input]
str_tmp = b'\xe6\x9f\xaf'
print("utf8解碼:",str_tmp.decode('utf-8'))
str_tmp = '柯'
print("utf8編碼:", str_tmp.encode('utf-8'))
str_tmp = '\u67ef'
print("utf8編碼:",str_tmp.encode('utf-8'))
str1 = "我愛祖國"
str2 = "I love my country"
print("utf8編碼:",str1.encode(encoding="utf8",errors="strict")) #等價於print("utf8編碼:",str1.encode("utf8"))
print("utf8編碼:",str2.encode(encoding="utf8",errors="strict"))
print("gb2312編碼:",str1.encode(encoding="gb2312",errors="strict"))#以gb2312編碼格式對str1進行編碼,獲得bytes類型對象的str
print("gb2312編碼:",str2.encode(encoding="gb2312",errors="strict"))
print("cp936編碼:",str1.encode(encoding="cp936",errors="strict"))
print("cp936編碼:",str2.encode(encoding="cp936",errors="strict"))
print("gbk編碼:",str1.encode(encoding="gbk",errors="strict"))
print("gbk編碼:",str2.encode(encoding="gbk",errors="strict"))
[output]
utf8解碼: 柯
utf8編碼: b'\xe6\x9f\xaf'
utf8編碼: b'\xe6\x9f\xaf'
utf8編碼: b'\xe6\x88\x91\xe7\x88\xb1\xe7\xa5\x96\xe5\x9b\xbd'
utf8編碼: b'I love my country'
gb2312編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gb2312編碼: b'I love my country'
cp936編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
cp936編碼: b'I love my country'
gbk編碼: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gbk編碼: b'I love my country'
參考文獻:
https://www.jianshu.com/p/4a043c3f8108
https://blog.csdn.net/qq_40678222/article/details/83033492
python2 相關:
https://www.zhihu.com/question/53470998
各類字符在線轉換:
http://tool.chinaz.com/tools/unicode.aspx
<< 未完待續