1. 程式人生 > >字符串與編碼,字符與數字相轉函數:ord(), chr()

字符串與編碼,字符與數字相轉函數:ord(), chr()

auto sci width white add () nbsp posit chm

編碼的發展過程:

美國ASCII碼:1個字節

各國編碼,如中國GB2312編碼:2個字節

統一編碼:Unicode 通常為2個字節,字節固定,浪費

UTF-8:將Unicode的字節 自動縮減合適字節存儲,字母為1個字節,普通漢字為3個字節


字符ASCIIUnicodeUTF-8
A0100000100000000 0100000101000001
01001110 0010110111100100 10111000 10101101

此表格參考:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819196283586a37629844456ca7e5a7faa9b94ee8000


ASCII字符與數字轉換:

#!/usr/bin/python

a = 65;
print ord('a'); #字符轉數字
print chr(a); #數字轉字符

技術分享圖片


漢字字符輸出:

#!/usr/bin/python
# -*- coding: utf-8 -*- ##告訴Python解釋器,按照UTF-8編碼讀取源代碼

print u'文'; #u'...' 用unicode編碼字符輸出

技術分享圖片



字符串與編碼,字符與數字相轉函數:ord(), chr()