这背后的设计思想是什么?
对我来说做这样的事情更容易
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 raiseValueError
when the substring is not found.
但是,正确测试子字符串成员资格的方法是使用in
:
if substring in string:
关于python - 为什么找不到子字符串时 Python 会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25916842/