【问题标题】:Python 2 to 3 = TypeError: descriptor 'find' for 'str' objects doesn't apply to a 'bytes' objectPython 2 到 3 = TypeError:“str”对象的描述符“find”不适用于“bytes”对象
【发布时间】:2021-03-24 22:23:34
【问题描述】:

您好,我们尝试将 python 2 转换为 3,但遇到错误。 也许有人有想法。

谢谢

if episode_num is not None:
                        episode_num = str.encode(str(episode_num), 'ascii','ignore')
                        if str.find(episode_num, ".") != -1:
                            splitted = str.split(episode_num, ".")
                            if splitted[0] != "":
                                #TODO fix dk format
                                try:
                                    season = int(splitted[0]) + 1
                                    is_movie = None # fix for misclassification
                                    if str.find(splitted[1], "/") != -1:
                                        episode = int(splitted[1].split("/")[0]) + 1
                                    elif splitted[1] != "":
                                        episode = int(splitted[1]) + 1
                                except:
                                    episode = ""
                                    season = ""

如果 str.find(episode_num, ".") != -1:

TypeError: 'str' 对象的描述符 'find' 不适用于 'bytes' 对象

https://www.dropbox.com/s/viszyzlpbl92yj0/source.py?dl=1

【问题讨论】:

  • 用你自己的话来说,你为什么要尝试使用类中的函数str.find,而不是仅仅在episode_num 上调用一个方法?你为什么要首先尝试.encode 字符串?
  • 请阅读nedbatchelder.com/text/unipain.html 并确保您了解 2.x 和 3.x 处理字节对象与字符串之间的区别。

标签: python-2to3


【解决方案1】:

Python 3 对于混合strbytes 字符串更加严格。只要保持一致。当您使用encode 时,您会创建一个bytes 字符串。

if bytes.find(episode_num, b".") != -1:

更好,学会使用in

if b"." in episode_num:

【讨论】:

    猜你喜欢
    • 2020-03-18
    • 2021-10-26
    • 2020-06-30
    • 2022-07-22
    • 2021-07-01
    • 2021-09-14
    • 2022-01-21
    • 2020-11-01
    • 2022-11-26
    相关资源
    最近更新 更多