你可以將一個字符串轉換成一串編碼,也可以轉換回來
1、編碼-encode()
Python encode() 方法以 encoding 指定的編碼格式編碼字符串。errors參數可以指定不同的錯誤處理方案。
str.encode(encoding='UTF-8',errors='strict')
參數
- encoding – 要使用的編碼,如"UTF-8"。
- errors – 設置不同錯誤的處理方案。默認爲 ‘strict’,意爲編碼錯誤引起一個UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通過 codecs.register_error() 註冊的任何值。
實例
>>> strs = '你好'
>>> strs.encode(0)
b'\xe4\xbd\xa0\xe5\xa5\xbd'
2、解碼-decode()
變成編碼的字符串可以再轉換回來,使用decode函數
>>> strs = '你好'
>>> strs.encode(0)
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> strs = b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> strs.decode()
'你好'