Pythonには部分文字列を探す文字列用の'contains'メソッドとかってある? [Python]

このエントリーをはてなブックマークに追加

質問:

string.contains とか string.indexofみたいなメソッドをPythonで探してるんだけど。やりたい事は:

if not somestring.contains("blah"):
continue

By Blankman | 質問日時: Aug 9 ‘10 at 2:52



回答1:

in演算子を使うといいよ:

if "blah" not in somestring:
continue

By Michael Mrozek | 回答日時: Aug 9 ‘10 at 2:56



回答2:

部分文字列検索の場合は string.find("substring")を使うことができるよ。

でもfindindexinを使う時はちょっと気をつけて。どうしてかって言うと、それらは部分文字列検索だから。言い換えれば、:

s = "This be a string"
if s.find("is") == -1:
print "No 'is' here!"
else:
print "Found 'is' in the string."

これはFound 'is' in the string.を出力するはず。同様に if "is" in s:Trueと評価されるはず。これは君が望むものかどうかわからないけど。

By eldarerathis | 回答日時: Aug 9 ‘10 at 2:55



Source: Does Python have a string ‘contains’ substring method?

共有 コメント