python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python encode()函数

Python编码解码之encode()函数详解

作者:士别三日wyx

这篇文章主要给大家介绍了关于Python编码解码之encode()函数的相关资料,Python的encode函数用于将字符串按照指定的编码方式进行编码,返回一个bytes类型的对象,需要的朋友可以参考下

encode

encode() 可以对字符串进行「编码」,常用来对「中文」字符串进行编码,以解决「乱码」问题。

语法

string.encode( encoding, errors )

参数

返回值

实例:对字符串进行GBK编码

str1 = 'hello'
print(str1.encode('gbk'))

输出:

b'hello'

1、常见编码格式

各个编码实例:

print('hello'.encode('gb2312'))
print('hello'.encode('gbk'))
print('hello'.encode('gb18030'))
print('hello'.encode('utf8'))
print('hello'.encode('utf16'))

输出:

b'hello'
b'hello'
b'hello'
b'hello'
b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'

仔细观察返回结果就会发现,字符串前面都加了个b,接下来我们了解一下这是什么含义。

2、返回的是Bytes类型

encode() 编码后会返回一个「Bytes类型」的结果,而不是「str类型」

str1 = 'hello'
print(type(str1))
print(type(str1.encode()))

输出:

<class 'str'>
<class 'bytes'>

bytes 和 str 都属于字符串类型:

bytes 是一个「二进制」序列对象,定义时在字符串前面加上b(英文可以,中文需要先encode)

str1 = b'hello'
print(type(str1))

输出:

<class 'bytes'>

3、错误处理方式

encode() 在编码时,经常会遇到「无法编码」的字符,这时就可以用 errors 设置适当的处理方式:

如果给「两个参数」,可以自动按顺序复制给参数;如果只给「一个参数」,需要用参数名指定。

print('hello'.encode('gbk', 'strict'))
print('hello'.encode(errors='ignore'))
print('hello'.encode(errors='backslashreplace'))
print('hello'.encode(errors='namereplace'))
print('hello'.encode(errors='replace'))
print('hello'.encode(errors='xmlcharrefreplace'))

4、解码

decode() 会将「bytes类型」转成「str类型」,这意味着它只能解码bytes类型的字符串,解码str类型的字符串会报错 AttributeError: ‘str’ object has no attribute ‘decode’

bytes类型格式是 b'xxx',如果只有str形式的字符串(比如 '\xe5\xbc\xa0\xe4\xb8\x89'),可以在前面加上b,变成bytes类型,再进行解码

print(b'\xe5\xbc\xa0\xe4\xb8\x89'.decode())

输出:

张三

总结

到此这篇关于Python编码解码之encode()函数的文章就介绍到这了,更多相关Python encode()函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文