Issue
In Python 2, I used to could do this:
>>> var='this is a simple string'
>>> var.encode('base64')
'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc=\n'
Easy! Unfortunately, this don't work in Python 3. Luckily, I was able to find an alternative way of accomplishing the same thing in Python 3:
>>> var='this is a simple string'
>>> import base64
>>> base64.b64encode(var.encode()).decode()
'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc='
But that's terrible! There has to be a better way! So, I did some digging and found a second, alternative method of accomplishing what used to be a super simple task:
>>> var='this is a simple string'
>>> import codecs
>>> codecs.encode(var.encode(),"base64_codec").decode()
'dGhpcyBpcyBhIHNpbXBsZSBzdHJpbmc=\n'
That's even worse! I don't care about the trailing newline! What I care about is, jeez, there's gotta to be a better way to do this in Python 3, right?
I'm not asking "why". I'm asking if there is a better way to handle this simple case.
Solution
So better is always subjective. One persons better solution can be anothers nightmare. For what its worth I wrote helper functions to do this:
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)
When ran it outputs the following:
b'c3RyaW5nIHRvIGVuY29kZQ=='
string to encode
Answered By - Robert H
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.