Python文字列find()メソッド
例
本文のどこに「ようこそ」という言葉がありますか?:
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
定義と使用法
このfind()
メソッドは、指定された値の最初の出現を検索します。
find()
値が見つからない場合、メソッドは-1を返します。
このfind()
方法はメソッドとほとんど同じですが
index()
、唯一の違いはindex()
、値が見つからない場合にメソッドが例外を発生させることです。(以下の例を参照)
構文
string.find(value, start, end)
パラメータ値
Parameter | Description |
---|---|
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
その他の例
例
テキストのどこに文字「e」が最初に出現しますか?:
txt = "Hello, welcome to my world."
x = txt.find("e")
print(x)
例
位置5と10の間でのみ検索した場合、テキストのどこに文字「e」が最初に出現しますか?:
txt = "Hello, welcome to my world."
x = txt.find("e",
5, 10)
print(x)
例
値が見つからない場合、find()メソッドは-1を返しますが、index()メソッドは例外を発生させます。
txt = "Hello, welcome to my world."
print(txt.find("q"))
print(txt.index("q"))