4

Base32 encoding in python 2.7 works like this:

$ python
Python 2.7.10 (default, Oct  6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> print(base64.b32encode("abc"))
MFRGG===

But when I try to do the same thing in python3 it fails. Why?

$ python
Python 3.7.2 (default, Jan 13 2019, 12:50:15)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import base64
>>> print(base64.b32encode("abc"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "my-virtual-env/lib/python3.7/base64.py", line 154, in b32encode
    s = memoryview(s).tobytes()
TypeError: memoryview: a bytes-like object is required, not 'str'
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

4

Answer:

print(base64.b32encode(bytearray("abc", 'ascii')).decode('utf-8'))
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
  • 3
    I'd consider `"abc".encode('ascii')` to be the more canonical solution (no need for the mutability of `bytearray` here, and the method self-documents better to my mind). Not a real critique, but it's weird to see `bytearray` in non-mutable contexts outside of the rare case of code that needs a `bytes`-like type that works on Py2 (where `bytes` aliases `str` and doesn't iterate by `int`). – ShadowRanger Jan 19 '19 at 04:19