嘿,我正试图将一些东西编码到base64,但我遇到了一个无效的格式错误。我不知道为什么有人可以帮助我:(
creqBytes = bytes(f'{"threeDSServerTransID":threeDSServerTransID,"transStatus":"Y","acsTransID":acsTransID,"messageType":"CRes","messageVersion":"2.1.0"}', 'utf-8')
creq2 = base64.b64encode(creqBytes).decode("ascii")
print(creq2)
您收到的ValueError: Invalid format specifier
错误消息来自第一行。这是因为在字符串之前有一个f
,表示这将是一个带有f字符串格式的字符串。但是,您没有在字符串中放入任何f字符串格式。因此出现了错误消息。
我可以通过删除f
来运行它。这是我的测试:
import base64
creqBytes = bytes('{"threeDSServerTransID":threeDSServerTransID,"transStatus":"Y","acsTransID":acsTransID,"messageType":"CRes","messageVersion":"2.1.0"}', 'utf-8')
print(creqBytes)
# b'{"threeDSServerTransID":threeDSServerTransID,"transStatus":"Y","acsTransID":acsTransID,"messageType":"CRes","messageVersion":"2.1.0"}'
creq2 = base64.b64encode(creqBytes).decode("ascii")
print(creq2)
# eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6dGhyZWVEU1NlcnZlclRyYW5zSUQsInRyYW5zU3RhdHVzIjoiWSIsImFjc1RyYW5zSUQiOmFjc1RyYW5zSUQsIm1lc3NhZ2VUeXBlIjoiQ1JlcyIsIm1lc3NhZ2VWZXJzaW9uIjoiMi4xLjAifQ==
然而,我怀疑这不是你想要做的。我的猜测是,你在Python中有一些变量想要包含在字符串中。如果是这种情况,那么f字符串看起来像:
import base64
threeDSServerTransID = 2
acsTransID = 3
creqBytes = bytes(f'{{"threeDSServerTransID":{threeDSServerTransID},"transStatus":"Y","acsTransID":{acsTransID},"messageType":"CRes","messageVersion":"2.1.0"}}', 'utf-8')
print(creqBytes)
# b'{"threeDSServerTransID":2,"transStatus":"Y","acsTransID":3,"messageType":"CRes","messageVersion":"2.1.0"}'
creq2 = base64.b64encode(creqBytes).decode("ascii")
print(creq2)
# eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6MiwidHJhbnNTdGF0dXMiOiJZIiwiYWNzVHJhbnNJRCI6MywibWVzc2FnZVR5cGUiOiJDUmVzIiwibWVzc2FnZVZlcnNpb24iOiIyLjEuMCJ9
f字符串的格式看起来很容易出错,其他人很难阅读。我怀疑,在进行base64编码之前,将数据作为Python字典并将其输出为JSON格式可能更容易理解和阅读。这看起来像:
import base64
import json
threeDSServerTransID = 2
acsTransID = 3
var1 = {
"threeDSServerTransID": threeDSServerTransID,
"transStatus": "Y",
"acsTransID": acsTransID,
"messageType": "CRes",
"messageVersion": "2.1.0"
}
var2 = json.dumps(var1)
print(var2)
# '{"threeDSServerTransID": 2, "transStatus": "Y", "acsTransID": 3, "messageType": "CRes", "messageVersion": "2.1.0"}'
var3 = base64.b64encode(var2.encode())
print(var3)
# b'eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IDIsICJ0cmFuc1N0YXR1cyI6ICJZIiwgImFjc1RyYW5zSUQiOiAzLCAibWVzc2FnZVR5cGUiOiAiQ1JlcyIsICJtZXNzYWdlVmVyc2lvbiI6ICIyLjEuMCJ9'
print(var3.decode('ascii'))
# eyJ0aHJlZURTU2VydmVyVHJhbnNJRCI6IDIsICJ0cmFuc1N0YXR1cyI6ICJZIiwgImFjc1RyYW5zSUQiOiAzLCAibWVzc2FnZVR5cGUiOiAiQ1JlcyIsICJtZXNzYWdlVmVyc2lvbiI6ICIyLjEuMCJ9