サイトアイコン Python Snippets

文字列検索系メソッド find, index, startswith, endswidth

find: 部分文字列を検索

指定した文字列内から、引数で与えた文字列が見つかるindexを返す。見つからない場合は−1を返す。

>>> "spam".find("pa")
1
>>> "spam".find("x")
-1

indexは見つからない場合にエラーを返す。

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

startswith: 指定した文字列で始まるかどうか?

>>> "spam".startswith("sp")
True
>>> "spam".startswith("pa")
False

endswith: 指定した文字列で終了するかどうか?

>>> "spam".endswith("am")
True
>>> "spam".endswith("x")
False
関連記事:

モバイルバージョンを終了