python string encode() 方法使用为其编码注册的编解码器对字符串进行编码。此函数基于指定的参数(即编码和错误)工作。
有各种类型的标准编码,例如 base64、ascii、gbk、hz、iso2022_kr、utf_32、utf_16 等等。根据指定的编码,对字符串进行编码。在此过程中,可以使用 errors 参数设置不同的错误处理方案。最后,此方法返回编码的字符串。
在下一节中,我们将了解有关 python 字符串 encode() 方法的更多详细信息。
语法
python string encode() 方法的语法如下。
Str.encode(encoding='UTF-8',errors='strict')
参数
以下是 python string encode() 函数的参数。
- encoding − 此参数指定要使用的编码。有关所有编码方案的列表,请访问:标准编码。
- errors − 此参数指定错误处理方案。errors 的默认值为 'strict',这意味着编码错误会引发 UnicodeError。其他可能的值是 'ignore'、'replace'、'xmlcharrefreplace'、'backslashreplace' 和通过 codecs.register_error() 注册的任何其他名称。
返回值
python 字符串 encode() 方法返回编码的字符串。
例将 'utf_16' 作为编码的 python string encode() 方法完成了可变长度编码。如果错误指定为 'strict',则编码错误会引发 UnicodeError。
在以下示例中,字符串 “Hello!Welcome to qikepu.“ 创建,并使用 encode() 函数对其进行编码。使用 print() 函数将编码的字符串打印为输出。在这种情况下,使用的编码是 'utf_16' ,使用的错误是 'strict' 。
str="Hello! Welcome to qikepu."
str_encoded= str.encode('utf_16','strict')
print("The encoded string is: ", str_encoded)
在执行上述程序时,将生成以下输出 -
例
将 'euc_kr' 作为其编码的 python string encode() 方法对韩文字符进行了可变长度编码。如果错误指定为 'strict',则编码错误会引发 UnicodeError。
在以下示例中,字符串 “Hello!Welcome to qikepu.“ 创建,并使用 encode() 函数对其进行编码。使用 print() 函数将编码的字符串打印为输出。在这两种情况下,使用的编码是 'euc_kr' ,使用的错误是 'strict' 。
str="Hello! Welcome to qikepu."
str_encoded= str.encode('euc_kr','strict')
print("The encoded string is: ", str_encoded)
以下是执行上述程序得到的输出 -
例
将 'utf_32' 作为其编码的 python string encode() 方法完成了可变长度编码。如果错误指定为 'replace',则将其替换为替换标记。这是在 replace_errors() 中实现的。
在以下示例中,字符串 “Hello!Welcome to qikepu.“ 创建,并使用 encode() 函数对其进行编码。使用 print() 函数将编码的字符串打印为输出。在这两种情况下,使用的编码是 'utf_32' ,使用的错误是 'replace'。
str="Hello! Welcome to qikepu."
str_encoded= str.encode('utf_32','replace')
print("The encoded string is: ", str_encoded)
通过执行上述程序获得以下输出 -
例
将 'utf_32' 作为其编码的 python string encode() 方法完成了可变长度编码。如果错误被指定为 'backslashreplace',它将实现 'backslashreplace' 错误处理。
在以下示例中,字符串 “Hello!Welcome to qikepu.“ 创建,并使用 encode() 函数对其进行编码。使用 print() 函数将编码的字符串打印为输出。在这两种情况下,使用的编码是 'utf_16_be' ,使用的错误是 'backslashreplace'。
str="Hello! Welcome to qikepu."
str_encoded= str.encode('utf_16_be','backslashreplace')
print("The encoded string is: ", str_encoded)
上述程序在执行时显示以下输出 -
例
不带任何参数的 python string encode() 函数采用编码的默认值并相应地执行。
在以下示例中,字符串 “Hello!Welcome to qikepu.“ 创建,并使用不带参数的 encode() 函数进行编码。使用 print() 函数将编码的字符串打印为输出。
str="Hello! Welcome to qikepu."
str_encoded= str.encode()
print("The encoded string is: ", str_encoded)
上述程序的输出显示如下 -