Pythonで文字列を検索する方法:含む判定と位置取得の完全ガイド

 

in演算子による含む判定

最も簡単な文字列検索方法はin演算子を使用することです。

text = "Pythonプログラミングは楽しい"

# 文字列が含まれるかチェック
if "Python" in text:
    print("Pythonが含まれています")

if "Java" not in text:
    print("Javaは含まれていません")

大文字小文字を無視した検索

text = "Hello, World!"
search_word = "hello"

if search_word.lower() in text.lower():
    print("大文字小文字を無視して見つかりました")

find()メソッドによる位置取得

基本的な位置検索

text = "Python is a great programming language"
position = text.find("great")
print(position)  # 12

# 見つからない場合は-1を返す
position = text.find("Java")
print(position)  # -1

検索開始位置の指定

text = "apple banana apple orange"
# 5文字目から検索開始
position = text.find("apple", 5)
print(position)  # 13

検索範囲の指定

text = "Hello, World! Hello, Python!"
# 0~15文字目の範囲で検索
position = text.find("Hello", 0, 15)
print(position)  # 0

index()メソッドによる位置取得

find()と似ていますが、見つからない場合に例外を発生させます。

text = "Python Programming"

try:
    position = text.index("Programming")
    print(f"見つかりました: {position}")
except ValueError:
    print("見つかりませんでした")

rfind()とrindex()による後方検索

最後の出現位置を検索

text = "apple banana apple orange apple"
last_position = text.rfind("apple")
print(last_position)  # 26

# 後方から検索範囲を指定
position = text.rfind("apple", 0, 20)
print(position)  # 13

count()メソッドによる出現回数

text = "apple banana apple orange apple"
count = text.count("apple")
print(count)  # 3

# 範囲指定での出現回数
count = text.count("apple", 10, 25)
print(count)  # 1

startswith()とendswith()

先頭・末尾のパターンチェック

filename = "data.csv"

if filename.endswith(".csv"):
    print("CSVファイルです")

if filename.startswith("data"):
    print("dataで始まるファイルです")

複数のパターンをチェック

filename = "script.py"
extensions = (".py", ".pyx", ".pyc")

if filename.endswith(extensions):
    print("Pythonファイルです")

正規表現による高度な検索

re.search()による初回マッチ

import re

text = "電話番号: 03-1234-5678"
pattern = r'\d{2,4}-\d{4}-\d{4}'
match = re.search(pattern, text)

if match:
    print(f"見つかりました: {match.group()}")
    print(f"位置: {match.start()}-{match.end()}")

re.findall()によるすべてのマッチ

import re

text = "価格は1000円、送料は500円、税込み1100円です"
prices = re.findall(r'\d+円', text)
print(prices)  # ['1000円', '500円', '1100円']

re.finditer()による詳細なマッチ情報

import re

text = "メールアドレス: test@example.com, admin@site.org"
pattern = r'[\w.-]+@[\w.-]+\.\w+'

for match in re.finditer(pattern, text):
    print(f"メール: {match.group()}")
    print(f"位置: {match.start()}-{match.end()}")

実用的な活用例

ファイル拡張子のチェック

def get_file_type(filename):
    if filename.endswith(('.jpg', '.jpeg', '.png', '.gif')):
        return "画像ファイル"
    elif filename.endswith(('.mp4', '.avi', '.mov')):
        return "動画ファイル"
    elif filename.endswith(('.txt', '.md', '.py')):
        return "テキストファイル"
    else:
        return "不明な形式"

print(get_file_type("image.jpg"))  # 画像ファイル

URLの検証

import re

def is_valid_url(url):
    pattern = r'https?://[\w.-]+\.\w+/?.*'
    return bool(re.match(pattern, url))

urls = [
    "https://www.example.com",
    "http://test.org/path",
    "invalid-url"
]

for url in urls:
    print(f"{url}: {is_valid_url(url)}")

テキスト内のキーワード検索

def search_keywords(text, keywords):
    found_keywords = []
    text_lower = text.lower()
    
    for keyword in keywords:
        if keyword.lower() in text_lower:
            # 実際の出現位置を取得
            position = text_lower.find(keyword.lower())
            found_keywords.append((keyword, position))
    
    return found_keywords

text = "PythonとJavaScriptでWeb開発を学習中"
keywords = ["Python", "Java", "Web", "AI"]
results = search_keywords(text, keywords)

for keyword, pos in results:
    print(f"{keyword}: 位置{pos}")

ログファイルの検索

import re

def search_log_errors(log_content):
    error_pattern = r'ERROR.*?(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}).*'
    errors = []
    
    for line_num, line in enumerate(log_content.splitlines(), 1):
        if "ERROR" in line:
            match = re.search(error_pattern, line)
            if match:
                errors.append({
                    'line': line_num,
                    'content': line.strip(),
                    'timestamp': match.group(1) if match else None
                })
    
    return errors

log_sample = """
2024-08-06 10:30:15 INFO Application started
2024-08-06 10:31:20 ERROR Database connection failed
2024-08-06 10:32:10 INFO Retrying connection
2024-08-06 10:33:05 ERROR Authentication error
"""

errors = search_log_errors(log_sample)
for error in errors:
    print(f"行{error['line']}: {error['content']}")

パフォーマンス比較

単純検索の速度比較

import time

text = "Python programming" * 10000
search_term = "programming"

# in演算子
start = time.time()
for _ in range(1000):
    result = search_term in text
time_in = time.time() - start

# find()メソッド
start = time.time()
for _ in range(1000):
    result = text.find(search_term) != -1
time_find = time.time() - start

print(f"in演算子: {time_in:.6f}秒")
print(f"find(): {time_find:.6f}秒")

高度な検索テクニック

曖昧検索(類似度計算)

def simple_similarity(s1, s2):
    """簡単な類似度計算"""
    s1, s2 = s1.lower(), s2.lower()
    common = sum(1 for a, b in zip(s1, s2) if a == b)
    return common / max(len(s1), len(s2))

def fuzzy_search(text, query, threshold=0.7):
    words = text.split()
    matches = []
    
    for word in words:
        similarity = simple_similarity(word, query)
        if similarity >= threshold:
            matches.append((word, similarity))
    
    return sorted(matches, key=lambda x: x[1], reverse=True)

text = "Python programming language development"
results = fuzzy_search(text, "programing")  # タイポあり
print(results)  # [('programming', 0.9)]

複数条件での検索

def multi_condition_search(text, conditions):
    """AND、OR、NOT条件での検索"""
    results = {
        'and_match': all(cond in text for cond in conditions.get('and', [])),
        'or_match': any(cond in text for cond in conditions.get('or', [])),
        'not_match': not any(cond in text for cond in conditions.get('not', []))
    }
    return all(results.values())

text = "Python web development with Django framework"
conditions = {
    'and': ['Python', 'web'],
    'or': ['Django', 'Flask'],
    'not': ['Java']
}

if multi_condition_search(text, conditions):
    print("条件にマッチしました")

まとめ

Pythonの文字列検索は用途に応じて適切なメソッドを選択することが重要です:

  • 単純な含む判定:in演算子
  • 位置取得:find()/index()
  • 出現回数:count()
  • 先頭・末尾チェック:startswith()/endswith()
  • 複雑なパターン:正規表現(reモジュール)

これらを組み合わせることで、効率的で柔軟な文字列検索が実現できます。

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>ゼロから始めるPython爆速講座