“TypeError:string参数没有编码”,但是字符串是编码的吗?

2024-05-05 01:07:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在把一个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: string argument without an encoding

我试着用不同的方法做这些,所有的错误都有不同的类型。

  • + str(bytes('timestamp', 'utf-8'))))
    • TypeError: Unicode-objects must be encoded before hashing
  • + str('timestamp', 'utf-8')))
    • TypeError: decoding str is not supported

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

谢谢!


Tags: 方法用户self程序tokenurlbytestime
1条回答
网友
1楼 · 发布于 2024-05-05 01:07:14

这个错误是由于在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

我希望能帮上忙!祝您有个美好的一天!

相关问题 更多 >