【问题标题】:"TypeError: string argument without an encoding", but the string is encoded?“TypeError:没有编码的字符串参数”,但字符串是编码的?
【发布时间】:2016-10-02 18:40:08
【问题描述】:

我正在努力将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 有初级到中级的知识),所以我对这门语言还不是很熟悉。有人对这个问题可能有什么想法吗?

谢谢!

【问题讨论】:

  • 我注意到链接中的代码已将该行更改为+ str(timestamp)).hexdigest()) 这可能需要做什么?
  • str(bytes('timestamp').encode('utf-8')) - 什么鬼?你想在那里做什么?
  • @TadhgMcDonald-Jensen 原来是这样,但是当我尝试运行脚本时(例如+ str(b'timestamp').hexdigest()))),我收到了AttributeError: 'str' object has no attribute 'hexdigest' 作为回报。可能是,但我不太确定这一点。
  • @user2357112 我一直在尝试各种组合来使这条线正确,今天它经历了许多形式......最终,我试图让这个整数转换为一种格式Py3 将被视为有效。
  • 你明白timestamp 是一个名字,'timestamp' 是一个字符串文字(与timestamp 名字无关)吗?这里不需要字节。在 Python 中将整数转换为字符串:str(timestamp)。使用urllib.parse.urlencode() 创建查询。传递 str 对象(Python 中的 Unicode)。您可能需要在.hexdigest() 结果上调用.decode('ascii', 'strict'),以获取str 而不是bytes

标签: python string python-3.x encoding utf-8


【解决方案1】:

这个错误是由于你在 python 3 中创建字节的方式造成的。

您不会使用bytes("bla bla"),而只需使用b"blabla",或者您需要指定像bytes("bla bla","utf-8") 这样的编码类型,因为它需要在将其转换为数字数组之前知道原始编码是什么。

然后报错

TypeError: string argument without an encoding

应该消失。

你有字节或字符串。如果你有一个 bytes 值并且你想把它变成 str 你应该这样做:

my_bytes_value.decode("utf-8")

它会返回一个str。

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

【讨论】:

  • 您好,感谢您的回复!所以,我首先尝试将它重写为b'timestamp',但这给了我TypeError: Can't convert 'bytes' object to str implicitly。相反,我尝试做str(b'timestamp'),但这会输出TypeError: Unicode-objects must be encoded before hashing。您的解释是有道理的,但我只是很难弄清楚将值作为字符串返回。我尝试使用decode("utf-8"),但无济于事。有什么想法或想法吗?
  • bytes('timestamp','utf-8')
  • 现在我收到了TypeError: urlopen() got an unexpected keyword argument 'encoding'
猜你喜欢
  • 2019-01-28
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 2017-03-23
  • 2020-04-22
  • 2016-12-30
相关资源
最近更新 更多