新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python encode()
python 中的encode()函數(shù)有助于將給定的字符串轉(zhuǎn)換為編碼格式。如果未指定編碼,默認(rèn)情況下將使用 UTF-8。

創(chuàng)新互聯(lián)從2013年成立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項目成都做網(wǎng)站、網(wǎng)站制作網(wǎng)站策劃,項目實(shí)施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元唐山做網(wǎng)站,已為上家服務(wù),為唐山各地企業(yè)和個人服務(wù),聯(lián)系電話:028-86922220
**string.encode(encoding='UTF-8',errors='strict')** #where encodings being utf-8, ascii, etc
編碼()參數(shù):
encode()函數(shù)接受兩個可選參數(shù)。這里的參數(shù)錯誤有六種類型。
- 失敗時的嚴(yán)格默認(rèn)響應(yīng)。
- 忽略-忽略不可編碼的 unicode
- replace -將不可編碼的 unicode 替換為問號(?)
- XML arreffreplace-它不是不可編碼的 unicode,而是插入 XML 字符引用
- backslashreplace 插入\ uNNNN 轉(zhuǎn)義序列,而不是不可編碼的 unicode
- 名稱替換-它插入了一個\N{而不是不可編碼的 unicode...}轉(zhuǎn)義序列
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 編碼 | 字符串必須編碼到的編碼類型 | 可選擇的 |
| 錯誤 | 編碼失敗時的響應(yīng) | 可選擇的 |
編碼()返回值
默認(rèn)情況下,函數(shù)使用 utf-8 編碼,如果出現(xiàn)任何故障,它會引發(fā)一個 UnicodeDecodeError 異常。
| 投入 | 返回值 | | 線 | 編碼字符串 |
Python 中encode()方法的示例
示例 1:如何將字符串編碼為默認(rèn)的 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:編碼如何處理錯誤參數(shù)?
# 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!' 文章名稱:創(chuàng)新互聯(lián)Python教程:Python encode()
文章起源:http://www.fisionsoft.com.cn/article/djeepoh.html


咨詢
建站咨詢
