Idris Hanafi Idris Hanafi - 7 months ago 114
Python Question

How to encode a string with base64 in python 3 and remove the new lines


I'm trying to encode my string of a username and password to base 64 for a SOAP request in python 3.5.2.


username = 'Universal API/uAPI7054626850-8a6c09f0'
password = 'gaghw3d5WCw3QCzTMh3QJ5fDp'
base64string = '%s:%s' % (username, password)
resultValue = base64string.encode('base64', 'strict')

This code has been exactly copied from the example at:


Traceback (most recent call last):
File "", line 44, in <module>
resultValue = base64string.encode('base64', 'strict')
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs


Attempt 1: using the base64 codec
base64string = base64.encodestring(base64string).replace('\n', '')
Result: TypeError: expected bytes-like object, not str

If you have any idea how to encode a string to the base64 codec please let me know. Thanks


Little did I know that the error came from the replace function being used after encoding the string. Use b64encode so that you don't have to write your own replace function to replace the new lines.


Try this:

base64string = base64.b64encode( bytes(base64string, "utf-8") )