Python3 encode(encoding='UTF-8',errors='strict') 方法

Python3 字符串


描述

encode() 方法以指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

语法

encode()方法语法:

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

参数

  • encoding -- 要使用的编码,如: UTF-8。
  • errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回值

该方法返回编码后的字符串,它是一个 bytes 对象。

实例

以下实例展示了 encode()函数的使用方法:

#!/usr/bin/python3
 
str = "IT自习室";
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'))

以上实例输出结果如下:

IT自习室
UTF-8 编码: b'IT\xe8\x87\xaa\xe4\xb9\xa0\xe5\xae\xa4'
GBK 编码: b'IT\xd7\xd4\xcf\xb0\xca\xd2'
UTF-8 解码: IT自习室
GBK 解码: IT自习室

Python3 字符串

本教程仅供参考学习,如用于商业带来的问题,本站概不负责。
关注公众号
关注公众号

©2020 IT自习室京ICP备20010815号