gpt4 book ai didi

python - "TypeError: string argument without an encoding",但字符串已编码?

转载 作者:太空狗 更新时间:2023-10-30 00:34:52 26 4
gpt4 key购买 nike

我正在努力转换 existing program从 Python2 到 Python3。该程序中的一种方法使用远程服务器对用户进行身份验证。它将提示用户输入密码。

def _handshake(self):
timestamp = int(time.time())
token = (md5hash(md5hash((self.password).encode('utf-8')).hexdigest()
+ str(bytes('timestamp').encode('utf-8'))))
auth_url = "%s/?hs=true&p=1.2&u=%s&t=%d&a=%s&c=%s" % (self.name,
self.username,
timestamp,
token,
self.client_code)
response = urlopen(auth_url).read()
lines = response.split("\n")
if lines[0] != "OK":
raise ScrobbleException("Server returned: %s" % (response,))
self.session_id = lines[1]
self.submit_url = lines[3]

这种方法的问题是整数转换为字符串后,需要进行编码。但据我所知,它已经编码了吗?我找到了 this question但我很难将其应用到该程序的上下文中。

这条线给我带来了问题。

  • + str(bytes('timestamp').encode('utf-8'))))
    • TypeError:没有编码的字符串参数

我尝试过尝试其他方法来完成此操作,但都出现了不同类型的错误。

  • + str(bytes('timestamp', 'utf-8'))))
    • TypeError:Unicode 对象必须在散列之前编码
  • + str('timestamp', 'utf-8')))
    • TypeError:不支持解码 str

我仍在开始学习 Python(但我对 Java 有初级到中级的了解),所以我还不完全熟悉这门语言。有人对这个问题可能有什么想法吗?

谢谢!

最佳答案

此错误是由于您在 python 3 中创建字节的方式所致。

你不会做 bytes("bla bla") 而只是 b"blabla" 或者你需要指定一个编码类型,比如 bytes("bla bla","utf-8") 因为在将其转换为数字数组之前,它需要知道原始编码是什么。

然后报错

TypeError: string argument without an encoding

应该消失。

您有 bytes 或 str。如果你有一个 bytes 值并且你想在 str 中转换它,你应该这样做:

my_bytes_value.decode("utf-8")

它会返回一个 str。

希望对您有所帮助!祝你今天过得愉快 !

关于python - "TypeError: string argument without an encoding",但字符串已编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37601804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com