在Python2.x和Python3.x中将字符串编码为base64

在Python2.x和Python3.x中将字符串编码为base64,python,python-3.x,encoding,base64,python-2.x,Python,Python 3.x,Encoding,Base64,Python 2.x,在Python 2中,我曾经可以这样做: >>> var='this is a simple string' >>> var.encode('base64') 'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc=\n' 轻松点!不幸的是,这在Python3中不起作用。幸运的是,我能够找到一种在Python 3中完成相同任务的替代方法: >>> var='this is a simple string' >>>

在Python 2中,我曾经可以这样做:

>>> var='this is a simple string'
>>> var.encode('base64')
'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc=\n'
轻松点!不幸的是,这在Python3中不起作用。幸运的是,我能够找到一种在Python 3中完成相同任务的替代方法:

>>> var='this is a simple string'
>>> import base64
>>> base64.b64encode(var.encode()).decode()
'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc='
但那太可怕了!一定有更好的办法!因此,我做了一些挖掘,找到了第二种替代方法来完成曾经非常简单的任务:

>>> var='this is a simple string'
>>> import codecs
>>> codecs.encode(var.encode(),"base64_codec").decode()
'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc=\n'
那更糟!我不在乎尾随的新线!我关心的是,老天,在Python3中必须有更好的方法来实现这一点,对吗


我不是问“为什么”。我在问是否有更好的方法来处理这个简单的案例。

所以更好总是主观的。一个人更好的解决方案可能是另一个人的噩梦。为此,我编写了帮助函数:

import base64

def base64_encode(string: str) -> str:
    '''
    Encodes the provided byte string into base64
    :param string: A byte string to be encoded. Pass in as b'string to encode'
    :return: a base64 encoded byte string
    '''
    return base64.b64encode(string)


def base64_decode_as_string(bytestring: bytes) -> str:
    '''
    Decodes a base64 encoded byte string into a normal unencoded string
    :param bytestring: The encoded string
    :return: an ascii converted, unencoded string
    '''
    bytestring = base64.b64decode(bytestring)
    return bytestring.decode('ascii')


string = b'string to encode'
encoded = base64_encode(string)
print(encoded)
decoded = base64_decode_as_string(encoded)
print(decoded)
运行时,它输出以下内容:

b'c3RyaW5nIHRvIGVuY29kZQ=='
string to encode

b64encode
在python3中需要一个类似字节的对象,因此在使用它之前,您必须将字符串转换为字节数组。请查看有关进行此更改的原因的详细解释。如果你觉得它太冗长了,就把它包装成一个函数。那么在Python3中没有更好的方法来实现这一点,你是这么说的吗?可能是重复的我只是好奇,Python3的方法有什么“糟糕”的地方?您必须
encode()?这只是一个额外的电话,但还是在一条线上。总比没有好。我做了类似的事情,但它在函数本身中编码为字节。应该有更好的方法来执行这样一个简单的字符串到字符串的转换。