【问题标题】:TypeError: list indices must be integers, not str (Python) [duplicate]TypeError:列表索引必须是整数,而不是str(Python)[重复]
【发布时间】:2018-01-21 06:40:57
【问题描述】:

首先,我想澄清一下,我已经阅读并研究过这个错误……而且我已经阅读了 stackoverflow 中的一些其他问题。然而,他们并没有帮助解决这个问题。 我编写的程序应该在某人过生日时给你一个通知(我在另一个 txt 文件中有日期)。但是,虽然当我运行该程序时它工作正常,直到它进入最后一个 if 语句。然后它给出了 List 索引必须是整数或切片,而不是 str 的错误。

import time
import os

with open("file_path") as file:
birthdays = file.readlines()

while True:
    import time
    date = str((time.strftime("%d/%m")))
    for i in birthdays:
        if date == birthdays[i]:
            os.system("""osascript -e 'display notification "{}" with title "{}"'""".format("Someone Has A Birthday Today", "Birthday"))

提前致谢,
克里斯

【问题讨论】:

  • 您需要date == i,因为i 不是索引。

标签: python string list indices


【解决方案1】:

您正在尝试为今天发生的每个生日致电os.system 一次。以下是你应该做的:

date = str((time.strftime("%d/%m")))
for i in birthdays:
    if date == i:

当您for-in 循环或迭代列表时,您将获得列表中的项目,而不是项目的索引。您不需要其他订阅。

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2014-09-02
    • 1970-01-01
    相关资源
    最近更新 更多