How to fix "TypeError: slice indices must be integers or None or have an __index__ method" error

How to fix "TypeError: slice indices must be integers or None or have an __index__ method" error

我试图在不和谐机器人的“选择数字”游戏中区分作为数字的不和谐消息和作为字母的不和谐消息。我想我可以只使用 startswith 参数来查看消息是否包含数字,但它 returns 一个 "TypeError: slice indices must be integers or None or have an index method" 每当我尝试它。我该如何解决这个问题?

if current_guess.startswith('1','2','3'):
            current_guess = int(current_guess)
            if best_id == "N/A":
                best_guess = current_guess
                best_id = current_id
            else:
                if abs(current_guess-number)<abs(best_guess-number):
                    best_guess = current_guess
                    best_id = current_id
                else:
                    return

因为 startswith 只允许搜索 3 个参数,所以我将这段代码复制了 3 次,每次检查数字 1-9 中的三个。

我期待它能够检测消息是否由数字组成,但它只是输出一个我不明白的错误。

 line 57, in PAN
    if current_guess.startswith('1','2','3'):
TypeError: slice indices must be integers or None or have an __index__ method

startswith 只接受 一个 字符串进行搜索;你可以把你的条件写成:

if any(guess.startswith(n) for n in ('1', '2', '3'))):
    ....

如果您只想知道字符串的第一个字符是否是数字,您也可以使用 isdigit(尽管这也匹配 '0'):

if guess[0].isdigit():
    ...

根据您真正想要查找的内容,您也可以考虑 re module:

if re.match('^[1-9]', guess)):
    ...

其中 ^ 表示字符串的 geginning,[1-9] 将匹配 '1''9'.

范围内的字符之一

如果我对你的问题理解正确,你想检查消息是否是数字。您可以使用 try / except:

try:
    current_guess = int(current_guess)

except ValueError:
    # warn user about only being possible to send digits