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

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]Search or Scanfor Excel book 【Python】ファイル名からExcelブックを取得する|openpyxl or win32com -
[Python]Excel datapandas.DataFrame 【Python】シートにあるデータを配列に格納する|pandas.DataFrame -
[Python]endswith+ lower 【Python】拡張子の存在確認|endswith + lower(Method Chaining) -
[Python]pathlib存在確認 【Python】フォルダとファイルの存在確認|pathlib -
[Python]Write a 1D arrayvia pandas 【Python】Excelに書き出す|pandas.ExcelWriter -
[Python]Excelto CSV 【Python】ExcelからCSVに書き出す|pandas,csv