python3.X decode()问题

python3.X decode()问题
2018年04月11日 12:05:57 like学 阅读数:2295
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/science_Lee/article/details/79894483
菜鸟上这样介绍:

str.decode(encoding=‘UTF-8’,errors=‘strict’)
1
参数
encoding – 要使用的编码,如"UTF-8"。
errors – 设置不同错误的处理方案。默认为 ‘strict’,意为编码错误引起一个UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值。
返回值
该方法返回解码后的字符串。

实例
以下实例展示了decode()方法的实例:

#!/usr/bin/python
str = "this is string example....wow!!!";
str = str.encode('base64','strict');

print "Encoded String: " + str;
print "Decoded String: " + str.decode('base64','strict') 

以上实例输出结果如下:

Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=

Decoded String: this is string example....wow!!! 

但是 我们在pycharm 上运行是报错的

 str3 = str1.encode(encoding ='base64',errors = 'strict');
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

python3 不可以直接这样用的:

import base64

需要这样

str1 = "this is string example....wow!!!"

str3 转成bytes 的string

str3 = str1.encode(encoding ='utf-8',errors = 'strict');
print (str3),
print ('')

bytes 再进行 base64 编码

str4= base64.b64encode(str3)

print (str4)
print ('')

再base64 decode 一下

print (str4.decode())
print ('')

base64 解码

enstr = base64.b64decode(str4.decode())
print(enstr.decode())

打印

b'this is string example....wow!!!'

b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='

dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=

this is string example....wow!!!

猜你喜欢

转载自blog.csdn.net/u013043762/article/details/86573552