python - 为什么找不到子字符串时 Python 会抛出错误?

标签 python string

这背后的设计思想是什么?

对我来说做这样的事情更容易

if string.index(substring) > -1:
    # do stuff

而不是试图捕捉异常。如果未找到 substring,至少您的程序不会中断。

有人告诉我“返回 -1 是一种糟糕的模式”。这是为什么?

检查子字符串的 Pythonic 方法是什么?

最佳答案

str.index() 抛出异常;你可能在想 str.find() method相反:

if string.find(substring) > -1:

str.index() documentation明确指出:

Like find(), but raise ValueError when the substring is not found.

但是,正确测试子字符串成员资格的方法是使用in:

if substring in string:

关于python - 为什么找不到子字符串时 Python 会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25916842/

相关文章:

python - EOFError : Ran out of input, 使用 torch.load()

string - listunagg函数?

c - 使用 fscanf 从文件中读取字符串后读取整数

c - 字符串的声明和初始化

java - 如何区分String中的两个字符串?(如何防止明文注入(inject))

python - 如何将带有空格的字符串作为关键字参数传递?

Python, SOAP 水,管理数组答案

python - 解析 XML 时出现 xml.parsers.expat.ExpatError

c++ - 输入被切断

python - Sympy Subs 在更换电源时不更换符号