Python 错误B64编码类似字节的对象是必需的,而不是';str';蟒蛇3

Python 错误B64编码类似字节的对象是必需的,而不是';str';蟒蛇3,python,python-3.x,token,Python,Python 3.x,Token,我在将Base64转换为python时出错,我找不到解决方案 uniq_token_hash = hashlib.sha256(uniq_token_string.encode('UTF-8')).hexdigest() print ('UNIQ HASH: %s' % uniq_token_hash) auth_token = b64encode('%s;%s;%s' % (devapp,unix_timestamp, uniq_token_hash)) print ('AUTH TOKEN:

我在将Base64转换为python时出错,我找不到解决方案

uniq_token_hash = hashlib.sha256(uniq_token_string.encode('UTF-8')).hexdigest()
print ('UNIQ HASH: %s' % uniq_token_hash)
auth_token = b64encode('%s;%s;%s' % (devapp,unix_timestamp, uniq_token_hash))
print ('AUTH TOKEN: %s' % auth_token)

line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

您必须将UTF-8字符串转换为简单的字节数组,您可以使用以下代码将字符串转换为字节数组

old_string = "string"
byte_array = old.string.encode()
# returns b'string'
new_string = byte_array.decode()
在最近的Python版本中,我将使用f'字符串。也许可以用这样的方式:

byte_array = f'{devapp};{unix_timestamp};{uniq_token_hash}'.encode()
auth_token = b64encode(byte_array)

请记住,您必须小心处理编码,并清楚地知道如何存储内容。

Python中有两种字符串。第一个由Unicode码点(字符)组成,称为
str
。第二个是字节序列(从0到255的小整数),它被称为
字节
B64编码
需要
字节
作为输入。您已经知道如何将
str
转换为
bytes
,因为您曾经使用
.encode
进行过一次转换

auth_token = b64encode(('%s;%s;%s' % (devapp,unix_timestamp, uniq_token_hash)).encode('UTF-8'))

谢谢@mark ransom,这是完美的密码