7

my script includes this line:

encoded = "Basic " + s.encode("base64").rstrip()

But gives me back the error:

LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

This line seemed to work fine in python 2 but since switching to 3 I get the error

3
  • Yes, this string codec was removed in Python 3 Commented Oct 3, 2017 at 14:24
  • If you want to do Base64 encoding in Python 3, you'd probably want to use the base64 module. Commented Oct 3, 2017 at 14:25
  • ^Of which was just showed by @warvariuc in his answer. Commented Oct 3, 2017 at 14:26

2 Answers 2

9

This string codec was removed in Python 3. Use base64 module:

Python 3.6.1 (default, Mar 23 2017, 16:49:06)

>>> import base64
>>> base64.b64encode('whatever')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
>>> base64.b64encode(b'whatever')
b'd2hhdGV2ZXI='
>>>

Don't forget to convert the data to bytes.

Sign up to request clarification or add additional context in comments.

6 Comments

In addition to this, you may want to use bytes() to convert a str to a bytes-like object. For example, bytes('python3', 'utf-8') would give us b'python3'.
It wasn't removed, it just can't be used with str.encode() anymore because it translates bytes to bytes and is not a text encoding for that reason. codecs.encode(b'whatever', 'base64') is closer to what was used in python2, and you don't have to remember which module to import for which codec.
@mata I meant it was removed from codecs available in string. bytes objects don't have encode.
@warvariuc, that would do then. Then again, both will still produce the same output anyways. Are there any performance differences between str.encode() and bytes()?
@SeanFrancisN.Ballais Don't estimate, measure! :)
|
5

Code as follows:

base64.urlsafe_b64encode('Some String'.encode('UTF-8')).decode('ascii')

For example: return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}

Worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.