Python 的 str.encode(~) 方法使用指定的編碼對字符串進行編碼。默認是使用 UTF-8 進行編碼。
參數
1.encoding | encoding type | optional
要使用的編碼類型。默認為 UTF-8 。
2. errors | error method | optional
指定如何處理錯誤。默認為 strict 。
|
類型 |
說明 |
|---|---|
|
|
編碼失敗時引發 |
|
|
忽略格式錯誤的數據並繼續,恕不另行通知。 |
|
|
更換合適的替換標記;對於編碼,這是 |
|
|
替換為適當的 XML 字符引用。 |
|
|
替換為反斜杠轉義序列。 |
|
|
替換為 |
返回值
作為字節對象的字符串的編碼版本。
例子
編碼參數
要使用 UTF-8 編碼 'marché':
x = 'marché'
x.encode()
b'march\xc3\xa9'
é 的 UTF-8 編碼表示為 \xc3\xa9,其中 \x 表示十六進製表示形式。
錯誤參數
使用 ascii 編碼和 'replace' 錯誤方法對 'marché' 進行編碼:
y = 'marché'
y.encode('ascii','replace')
b'march?'
無法用 ASCII 表示 é,因此使用 '?' 替換標記而不是引發錯誤。
使用 ascii 編碼和 'strict' 錯誤方法對 'marché' 進行編碼(默認):
z = 'marché'
z.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 5
由於無法用 ASCII 表示 é,因此會引發 UnicodeEncodeError。
相關用法
- Python String encode()用法及代碼示例
- Python String endswith方法用法及代碼示例
- Python String endswith()用法及代碼示例
- Python String expandtabs()用法及代碼示例
- Python String expandtabs方法用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String isidentifier()用法及代碼示例
- Python String startswith()用法及代碼示例
- Python String rjust方法用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String rpartition方法用法及代碼示例
- Python String ljust方法用法及代碼示例
- Python String splitlines()用法及代碼示例
- Python String upper()用法及代碼示例
- Python String isprintable()用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | encode method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
