Python3编码或不带字符串argumen的错误

2024-04-27 20:42:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python 2中有一个函数,用来从UUID生成一个22长度的随机字符串。。。。

def make_base64_string():
    return uuid.uuid4().bytes.encode("base64")[:22]

从那时起,我就开始用Python 3进行测试,并且刚刚看完Pragmatic Unicode presentation,其中大部分都超出了我的想象。无论如何,我不认为这个函数现在可以在Python3.4中工作,我是对的。。。。

所以接下来,我尝试了我希望的解决方案,因为我的理解已经消失了。。。(把一切都当作一个字节,对吧?)。

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 

为什么?我想了解更多。


Tags: 函数字符串stringmakereturnbytesuuiddef
2条回答

base64.b64encode以字节为参数,无需解码重新编码。

>>> base64.b64encode(uuid.uuid4().bytes)
b'58jvz9F7QXaulSScqus0NA=='
>>> base64.b64encode(uuid.uuid4().bytes)
b'gLV2vn/1RMSSckMd647jUg=='
>>> type(uuid.uuid4())
<class 'uuid.UUID'>

这表明uuid.uuid4()不是字符串,您需要将字符串传递到字节,因此下面是工作代码:

base64.b64encode(bytes(str(uuid.uuid4()), 'utf-8'))

相关问题 更多 >