Skip to main content
 首页 » 编程设计

没有字符串参数的 Python 3 编码或错误

2025年05月04日60pengyingh

我在 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=='