Python3 encode() Method

Python3 字符串Python3 Strings


Description

The encode() method encodes the string in the specified encoding format. The errors parameter can specify different error handling schemes.

Syntax

The syntax of the encode() method is:

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

Parameters

  • encoding -- The encoding to use, such as: UTF-8.
  • errors -- Sets the error handling scheme. The default is 'strict', meaning encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any value registered via codecs.register_error().

Return Value

This method returns the encoded string, which is a bytes object.

Examples

The following examples demonstrate the usage of the encode() method:

Examples (Python 3.0+)

#!/usr/bin/python3 str = "Example Tutorial"; str_utf8 = str.encode("UTF-8") str_gbk = str.encode("GBK") print(str) print("UTF-8 encoding:", str_utf8) print("GBK encoding:", str_gbk) print("UTF-8 decoding:", str_utf8.decode('UTF-8','strict')) print("GBK decoding:", str_gbk.decode('GBK','strict'))

The output of the above examples is as follows:

Example
UTF-8 编码: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
GBK 编码: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
UTF-8 解码: Example
GBK 解码: Example

Python3 字符串Python3 Strings

Other Extensions