一个字符串转换为从基地64 [英] Converting a string to and from Base 64

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

问题描述

我想写两个项目一个一个字符串转换为base64,然后另一个需要一个base64连接codeD字符串,并将其转换回字符串。结果
到目前为止,我不能让过去的base64编码一部分,我不断收到错误

 类型错误:预期的字节,而不是str的

我的code看起来像这样至今

 高清convertToBase64(stringToBeEn codeD):
进口的base64
恩codedString = base64.b64en code(stringToBeEn codeD)
收益率(恩codedString)


解决方案

一个字符串,已经是去codeD,从而str类没有'德code'function.Thus:

  AttributeError的:类型的对象'海峡'有'德code'没有属性

如果您想取消code字节数组,把它变成一个字符串电话:

  the_thing.de code(编码)

如果你想带code字符串(把它变成一个字节数组)调用:

  the_string.en code(编码)

在的底座64的东西方面:
使用的base64'作为上述编码值产生的错误:

  LookupError:未知编码:BASE64

打开以下控制台,然后键入:

 进口的base64
帮助的(Base64)

您将看到的base64有两个非常方便的功能,即b64de code和b64en code。 B64德code返回一个字节数组和b64en code需要一个字节数组中。

要转换一个字符串到它的base64重新presentation您首先需要将其转换为字节。我喜欢UTF-8,但使用任何你需要的编码...

 进口的base64
高清stringToBase64(S):
    返回base64.b64en code(s.en code(UTF-8))高清base64ToString(二):
    返回base64.b64de code(B)由Matchi.com提供回到code(UTF-8)

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)

解决方案

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

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

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