python 中的encode()
函數有助于將給定的字符串轉換為編碼格式。如果未指定編碼,默認情況下將使用 UTF-8。
**string.encode(encoding='UTF-8',errors='strict')** #where encodings being utf-8, ascii, etc
編碼()參數:
encode()
函數接受兩個可選參數。這里的參數錯誤有六種類型。
- 失敗時的嚴格默認響應。
- 忽略-忽略不可編碼的 unicode
- replace -將不可編碼的 unicode 替換為問號(?)
- XML arreffreplace-它不是不可編碼的 unicode,而是插入 XML 字符引用
- backslashreplace 插入\ uNNNN 轉義序列,而不是不可編碼的 unicode
- 名稱替換-它插入了一個\N{而不是不可編碼的 unicode...}轉義序列
參數 | 描述 | 必需/可選 |
---|---|---|
編碼 | 字符串必須編碼到的編碼類型 | 可選擇的 |
錯誤 | 編碼失敗時的響應 | 可選擇的 |
編碼()返回值
默認情況下,函數使用 utf-8 編碼,如果出現任何故障,它會引發一個 UnicodeDecodeError 異常。
| 投入 | 返回值 | | 線 | 編碼字符串 |
Python 中encode()
方法的示例
示例 1:如何將字符串編碼為默認的 Utf-8 編碼?
# unicode string
string = 'pyth?n!'
# print string
print('The original string is:', string)
# default encoding to utf-8
string_utf8 = string.encode()
# print result
print('The encoded string is:', string_utf8)
輸出:
The original string is: pyth?n!
The encoded string is: b'pyth\xc3\xb6n!'
示例 2:編碼如何處理錯誤參數?
# unicode string
string = 'pyth?n!'
# print string
print('The original string is:', string)
# ignore error
print('The encoded string (with ignore) is:', string.encode("ascii", "ignore"))
# replace error
print('The encoded string (with replace) is:', string.encode("ascii", "replace"))
輸出:
The original string is: pyth?n!
The encoded string (with ignore) is: b'pythn!'
The encoded string (with replace) is: b'pyth?n!'