【问题标题】:How to do Base32 encoding in python3?如何在 python3 中进行 Base32 编码?
【发布时间】:2019-06-13 07:12:51
【问题描述】:

python 2.7 中的 Base32 编码是这样工作的:

$ 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===

但是当我尝试在 python3 中做同样的事情时它失败了。为什么?

$ 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'

【问题讨论】:

标签: python python-3.x base32


【解决方案1】:

答案:

print(base64.b32encode(bytearray("abc", 'ascii')).decode('utf-8'))

【讨论】:

  • 我认为"abc".encode('ascii') 是更规范的解决方案(这里不需要bytearray 的可变性,并且我认为该方法更好地自我记录)。不是真正的批评,但是在需要在 Py2 上工作的类似 bytes 类型的代码的罕见情况之外的非可变上下文中看到 bytearray 很奇怪(其中 bytes 别名 str 并且没有t 迭代 int)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 2011-08-22
  • 2012-12-14
  • 2011-07-14
  • 1970-01-01
  • 2013-10-04
  • 2019-05-05
相关资源
最近更新 更多