在 Python 2.x 与 Python 3.x 中将字符串编码为 base64

Encoding a string to base64 in Python 2.x vs Python 3.x

在Python2中,我以前可以这样做:

>>> var='this is a simple string'
>>> var.encode('base64')
'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc=\n'

简单!不幸的是,这在 Python 3 中不起作用。幸运的是,我能够在 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'

更糟!我不在乎尾随的换行符!我关心的是,老天,在 Python 3 中 gotta 是一个更好的方法,对吧?

我不是在问 "why"。我在问是否有更好的方法来处理这个简单的案例。

所以更好总是主观的。一个人更好的解决方案可能是另一个人的噩梦。为了它的价值,我编写了辅助函数来做到这一点:

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