二十六、python中字符串的编码与解码,utf-8编码与解码,gbk编码与解码

在python中,我们经常会使用到字符串的编码与解码,推荐你在写代码的过程中都用utf-8编码解码

1、utf-8编码用函数encode,例子,编码英文跟数字的时候,他只是在前面多了个b,编码中文的时候,后面就改变了,直接看例子

string = 'abcdefg'
string.encode()
#输出结果是
b'abcdefg'
string = '郑王铭'
string.encode()
#输出结果是
b'\xe9\x83\x91\xe7\x8e\x8b\xe9\x93\xad'

2、utf-8解码用函数decode

string = '郑王铭'
bs = string.encode()
bs.decode()
#输出结果是
郑王铭

3、gbk编码一样是用encode函数,不过后面需要设置编码方式

string = '郑王铭'
string.encode(encoding = 'gbk')
#输出结果是
b'\xd6\xa3\xcd\xf5\xc3\xfa'

4、gbk解码一样是用decode函数,不过后面需要设置编码方式

string = '郑王铭'
bs = string.encode(encoding = 'gbk')
bs.decode(encoding = 'gbk')
#输出结果是
郑王铭

python关于字符串的编码与解码的讲到这里,有问题欢迎评论

猜你喜欢

转载自blog.csdn.net/u010590983/article/details/90069890
今日推荐