Base64编码错误,需要bytes-like对象,不是'str'

Base64 Error in encoding, bytes-like object is required, not 'str'

import base64
mycode = "print 'Hello World!'"
secret = base64.b64encode(mycode)
print(secret)

这段代码不起作用,它说需要类似字节的对象,而不是 'str'。 有人可以帮忙吗?

如消息所述,编码器需要字节,而不是字符串。所以将字符串转换为字节。

>>> secret = base64.b64encode(bytes(mycode,"UTF-8"))
>>> secret
b'cHJpbnQgJ0hlbGxvIFdvcmxkISc='
>>> base64.b64decode(secret)
b"print 'Hello World!'"

您是否正在遵循假定您在 Python 2 中工作的示例代码?