我在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
为什么?我想了解更多。
base64.b64encode以字节为参数,无需解码重新编码。
这表明uuid.uuid4()不是字符串,您需要将字符串传递到字节,因此下面是工作代码:
相关问题 更多 >
编程相关推荐