Python3 String Encode
# Python3.x Python3 encode() Method
[ Python3 Strings](#)
* * *
## Description
The `encode()` method encodes a string using the specified encoding. The `errors` parameter can be used to set a different error handling scheme.
## Syntax
The syntax for the `encode()` method is:
str.encode(encoding='UTF-8',errors='strict')
## Parameters
* `encoding` -- The encoding to use, e.g., UTF-8.
* `errors` -- Sets the error handling scheme. The default is 'strict', which means that 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 as a bytes object.
## Example
The following examples demonstrate the use of the `encode()` method:
## Example (Python 3.0+)
#!/usr/bin/python3 str = ""; str_utf8 = str.encode("UTF-8")str_gbk = str.encode("GBK")print(str)print("UTF-8 Encode: ", str_utf8)print("GBK Encode: ", str_gbk)print("UTF-8 Decode: ", str_utf8.decode('UTF-8','strict'))print("GBK Decode: ", str_gbk.decode('GBK','strict'))
The output of the above example is:
UTF-8 Encoding: b'xe8x8fx9cxe9xb8x9fxe6x95x99xe7xa8x8b' GBK Encoding: b'xb2xcbxc4xf1xbdxccxb3xcc' UTF-8 Decode: GBK Decode:
* * Python3 Strings](#)
YouTip