Python字串encode()方法

Python字串encode()方法返回字串的編碼版本。默認編碼是當前的默認字串編碼。 可以給出錯誤以設置不同的錯誤處理方案。

語法

以下是encode()方法的語法 -

str.encode(encoding = 'UTF-8',errors = 'strict')

參數

  • encoding - 這是要使用的編碼。有關所有編碼方案的列表,請訪問:標準編碼
  • errors - 可以給出這一點來設置不同的錯誤處理方案。錯誤的默認值為“strict”,這意味著編碼錯誤會引發UnicodeError。其他可能的值是“ignore”,“replace”,“xmlcharrefreplace”,“backslashreplace”以及通過codecs.register_error()註冊的任何其他名稱。

返回值

  • 此方法返回編碼後的字串

示例

以下示例顯示了encode()方法的用法。

#!/usr/bin/python3
import base64

str = "this is string example....wow!!!"
str = base64.b64encode(str.encode('utf-8',errors = 'strict'))

print ("Encoded String: " , str)

當運行上面的程式,它產生以下結果 -

Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='

上一篇: Python字串 下一篇: Python列表