python中encode()函数的用法

python字符串函数用法大全链接

encode()函数

描述:以指定的编码格式编码字符串,默认编码为 'utf-8'。

语法:str.encode(encoding='utf-8', errors='strict')     -> bytes (获得bytes类型对象)

  • encoding 参数可选,即要使用的编码,默认编码为 'utf-8'。字符串编码常用类型有:utf-8,gb2312,cp936,gbk等。
  • errors 参数可选,设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeEncodeError。 其它可能值有 'ignore', 'replace', 'xmlcharrefreplace'以及通过 codecs.register_error() 注册其它的值。

程序示例:

str1 = "我爱祖国"
str2 = "I love my country"
print("utf8编码:",str1.encode(encoding="utf8",errors="strict")) #等价于print("utf8编码:",str1.encode("utf8"))
print("utf8编码:",str2.encode(encoding="utf8",errors="strict"))
print("gb2312编码:",str1.encode(encoding="gb2312",errors="strict"))#以gb2312编码格式对str1进行编码,获得bytes类型对象的str
print("gb2312编码:",str2.encode(encoding="gb2312",errors="strict"))
print("cp936编码:",str1.encode(encoding="cp936",errors="strict"))
print("cp936编码:",str2.encode(encoding="cp936",errors="strict"))
print("gbk编码:",str1.encode(encoding="gbk",errors="strict"))
print("gbk编码:",str2.encode(encoding="gbk",errors="strict"))

程序运行结果:

utf8编码: b'\xe6\x88\x91\xe7\x88\xb1\xe7\xa5\x96\xe5\x9b\xbd'
utf8编码: b'I love my country'
gb2312编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gb2312编码: b'I love my country'
cp936编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
cp936编码: b'I love my country'
gbk编码: b'\xce\xd2\xb0\xae\xd7\xe6\xb9\xfa'
gbk编码: b'I love my country'

注:在python中encodedecode分别指编码和解码

猜你喜欢

转载自blog.csdn.net/qq_40678222/article/details/83033492