Python字符串encode() decode()

Python 字串 encode()

Python 字串 encode() 函數用於使用提供的編碼對字串進行編碼。此函數返回一個位元組對象。如果不提供編碼,則默認使用“utf-8”編碼。

Python 位元組 decode()

Python 位元組 decode() 函數用於將位元組轉換為字串對象。這兩個函數都允許我們指定用於編碼/解碼錯誤的錯誤處理方案。默認值為“strict”,意味著編碼錯誤會引發 UnicodeEncodeError。其他可能的值包括’ignore’、’replace’和’xmlcharrefreplace’。讓我們看一個簡單的 Python 字串 encode() decode() 函數的示例。

str_original = 'Hello'

bytes_encoded = str_original.encode(encoding='utf-8')
print(type(bytes_encoded))

str_decoded = bytes_encoded.decode()
print(type(str_decoded))

print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)

輸出:

<class 'bytes'>
<class 'str'>
Encoded bytes = b'Hello'
Decoded String = Hello
str_original equals str_decoded = True

上面的示例並未清楚展示編碼的使用。讓我們看另一個示例,其中我們將從用戶獲取輸入,然後進行編碼。我們將在用戶輸入的字串中包含一些特殊字符。

str_original = input('Please enter string data:\n')

bytes_encoded = str_original.encode()

str_decoded = bytes_encoded.decode()

print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)

輸出:

Please enter string data:
aåb∫cçd∂e´´´ƒg©1¡
Encoded bytes = b'a\xc3\xa5b\xe2\x88\xabc\xc3\xa7d\xe2\x88\x82e\xc2\xb4\xc2\xb4\xc2\xb4\xc6\x92g\xc2\xa91\xc2\xa1'
Decoded String = aåb∫cçd∂e´´´ƒg©1¡
str_original equals str_decoded = True

你可以從我們的 GitHub 存儲庫 檢查完整的 Python 腳本和更多 Python 示例。

參考:str.encode() API 文件,bytes.decode() API 文件

Source:
https://www.digitalocean.com/community/tutorials/python-string-encode-decode