1. ホーム
  2. python

[解決済み] findとindexの違い

2023-03-25 18:38:22

質問

私はpythonの初心者で、findとindexの違いがよくわかりません。

>>> line
'hi, this is ABC oh my god!!'
>>> line.find("o")
16
>>> line.index("o")
16

これらは常に同じ結果を返します。 ありがとうございます!

どのように解決するのですか?

str.find リターン -1 を返します。

>>> line = 'hi, this is ABC oh my god!!'
>>> line.find('?')
-1

一方 str.index レイズ ValueError :

>>> line.index('?')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

どちらの関数もサブストリングが見つかった場合、同じように動作します。