python3.X decode()问题

本文介绍了在Python3中使用decode()方法时遇到的问题,特别是当结合base64编码时。菜鸟教程提供了基本用法,但在PyCharm环境中直接使用会报错。正确使用方式是在调用decode()前先进行base64解码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

菜鸟上这样介绍:

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

参数
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!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值