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

标签 python python-3.x

我在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/

相关文章:

python - 在类初始化时使用数组中的变量定义函数

java - 找到一种有效的方法将不同的语言库集成到一个项目中,使用 Python 作为 "glue"

python - 使用 Pandas 选择满足特定条件的组中的所有元素

Python 正则表达式不提取值 - Python 3.x

python - 如何解析带有分数的字符串以获取 '/'两边的数字

python - 如何在 python 列表中追加字段值并忽略 None 值

python-3.x - 如何从csv获取数据到python对象中

python - 来自 Tensorflow 中的 sparse_softmax_cross_entropy_with_logits 的 NaN

python - 有没有办法为Python中的长字符串分配内存?

python - 将 PDF 转换为文本 - 保留表格行 - Python