【Python】指定の文字列が含まれているか|in
作成日:2025-10-04
更新日:2025-10-06

in 演算子(最もPythonic)
email = "name@example.com"
if "@" in email:
print("含まれている!")
else:
print("含まれていない")
in だけでわかる
if keyword in text:- 一番シンプルで読みやすい
- True/False を返すから、そのまま条件に使える
str.find()|位置を知りたいとき
pos = email.find("@")
if pos != -1:
print(f"位置は {pos}") # 0始まりのインデックスfindは「見つからないと -1」- 0始まり、見つからなければ -1
関数化する場合
def contains(text: str, keyword: str) -> bool:
return keyword in text
print(contains("hello world", "world")) # True
print(contains("hello world", "moon")) # False- 単純に含有判定 →
if keyword in text: - 位置が欲しい →
find() - ラップしたい → contains() 関数を作る
2025-10-04
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[Python]endswith+ lower 【Python】拡張子の存在確認|endswith + lower(Method Chaining) -

[Python]stripspace 【Python】先頭,末尾,両端の空白を削除する|.strip -

[Python]Pydantic:The data validation Python【What Is Pydantic?】The Data Validation Engine Behind FastAPI -

asynchronousasyncawait Python【async / await】非同期処理で止まらない世界を作る -

[Python]pathlib存在確認 【Python】フォルダとファイルの存在確認|pathlib -

[Python]datetimestring format time 【Python】文字列を日付型に変える|datetime.strftime