【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]Excel datapandas.DataFrame 【Python】シートにあるデータを配列に格納する|pandas.DataFrame -
[Python]Stringsplit 【Python】文字列を抜き出す|split -
[Python]Excelto CSV 【Python】ExcelからCSVに書き出す|pandas,csv -
[Python]getdictionary 【Python】dictionaryから値を取得する2つの違い -
[Python]list concatenation 【Python】配列(list)の結合|arr + arr , np.concatenate -
[Python]endswith+ lower 【Python】拡張子の存在確認|endswith + lower(Method Chaining)