我在Python 2中有一个函数,我用它从 UUID 生成 22 长度的随机字符串......
def make_base64_string():
return uuid.uuid4().bytes.encode("base64")[:22]
此后我开始在 Python 3 中进行测试,并刚刚看完 Pragmatic Unicode presentation ,其中大部分超出了我的理解范围。不管怎样,我不认为这个函数现在可以在 Python 3.4 中工作,我是对的......
接下来,我尝试了我所希望的解决方案,让我轻描淡写的 bytes.encode
消失了......(将所有内容都视为一个字节,对吧?)。
base64.b64encode(bytes(uuid.uuid4(), 'utf-8'))
但这给了我以下错误......
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: encoding or errors without a string argument
为什么?我想进一步了解这一点。
最佳答案
base64.b64encode 以字节为参数,无需解码-重新编码。
>>> base64.b64encode(uuid.uuid4().bytes)
b'58jvz9F7QXaulSScqus0NA=='
>>> base64.b64encode(uuid.uuid4().bytes)
b'gLV2vn/1RMSSckMd647jUg=='
关于Python 3 编码或没有字符串参数的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30396709/