将字符串转换为 Base 64 和从 Base 64 转换 [英] Converting a string to and from Base 64

查看:25
本文介绍了将字符串转换为 Base 64 和从 Base 64 转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写两个程序,一个将字符串转换为 base64,另一个将 base64 编码的字符串转换回字符串.
到目前为止,我无法通过 base64 编码部分,因为我不断收到错误

I am trying to write two programs one that converts a string to base64 and then another that takes a base64 encoded string and converts it back to a string.
so far i cant get past the base64 encoding part as i keep getting the error

TypeError: expected bytes, not str

到目前为止,我的代码看起来像这样

my code looks like this so far

def convertToBase64(stringToBeEncoded):
import base64
EncodedString= base64.b64encode(stringToBeEncoded)
return(EncodedString)

推荐答案

一个字符串已经被解码",所以str类没有解码"功能.因此:

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)

就 base 64 的东西而言:使用 'base64' 作为上述编码的值会产生错误:

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)

你会看到base64有两个非常方便的函数,分别是b64decode和b64encode.b64 decode 返回一个字节数组,b64encode 需要一个字节数组.

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.

要将字符串转换为 base64 表示,您首先需要将其转换为字节.我喜欢 utf-8,但使用你需要的任何编码......

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')

这篇关于将字符串转换为 Base 64 和从 Base 64 转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆