Latest web development tutorials

Python3 encode () method

Python3 string Python3 string


description

encode () method to specify the encoding format string. errors parameter can specify a different error handling scheme.

grammar

encode () method syntax:

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

parameter

  • encoding - The encoding to use, such as: UTF-8.
  • errors - set a different error handling scheme. The default is 'strict', meaning a coding error caused UnicodeError. Other values ​​may have to have 'ignore', 'replace', 'xmlcharrefreplace' 'backslashreplace' and no value registered by codecs.register_error ().

return value

This method returns a string encoded.

Examples

The following example shows an example of encode () method:

#!/usr/bin/python3

str = "本教程";
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")

print(str)

print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)

print("UTF-8 解码:", str_utf8.decode('UTF-8','strict'))
print("GBK 解码:", str_gbk.decode('GBK','strict'))

Examples of the above output results are as follows:

本教程
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 解码: 本教程
GBK 解码: 本教程

Python3 string Python3 string