python3转base64_如何从Base64转换为字符串Python 3.2

def convertFromBase64 (stringToBeDecoded):

import base64

decodedstring=str.decode('base64',"stringToBeDecoded")

print(decodedstring)

return

convertFromBase64(dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=)

I am tying to take a base64 encoded string and convert it back to the original string but I cant figure out quite what is wrong

I am getting this error

Traceback (most recent call last):

File "C:/Python32/junk", line 6, in

convertFromBase64(("dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE="))

File "C:/Python32/junk", line 3, in convertFromBase64

decodedstring=str.decode('base64',"stringToBeDecoded")

AttributeError: type object 'str' has no attribute 'decode'

解决方案

A string is already 'decoded', thus the str class has no 'decode' function.Thus:

AttributeError: type object 'str' has no attribute 'decode'

If you want to decode a byte array and turn it into a string call:

the_thing.decode(encoding)

If you want to encode a string (turn it into a byte array) call:

the_string.encode(encoding)

In terms of the base 64 stuff:

Using 'base64' as the value for encoding above yields the error:

LookupError: unknown encoding: base64

Open a console and type in the following:

import base64

help(base64)

You will see that base64 has two very handy functions, namely b64decode and b64encode. b64 decode returns a byte array and b64encode requires a bytes array.

To convert a string into it's base64 representation you first need to convert it to bytes. I like utf-8 but use whatever encoding you need...

import base64

def stringToBase64(s):

return base64.b64encode(s.encode('utf-8'))

def base64ToString(b):

return base64.b64decode(b).decode('utf-8')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值