Pythonにおけるfindメソッドを使った文字列検索の実例14選

Pythonのfindメソッドを学ぶ初心者向けイラストPython
この記事は約23分で読めます。

 

【サイト内のコードはご自由に個人利用・商用利用いただけます】

この記事では、プログラムの基礎知識を前提に話を進めています。

説明のためのコードや、サンプルコードもありますので、もちろん初心者でも理解できるように表現してあります。

基本的な知識があればカスタムコードを使って機能追加、目的を達成できるように作ってあります。

※この記事は、一般的にプロフェッショナルの指標とされる『実務経験10,000時間以上』を凌駕する現役のプログラマチームによって監修されています。

サイト内のコードを共有する場合は、参照元として引用して下さいますと幸いです

※Japanシーモアは、常に解説内容のわかりやすさや記事の品質に注力しております。不具合、分かりにくい説明や不適切な表現、動かないコードなど気になることがございましたら、記事の品質向上の為にお問い合わせフォームにてご共有いただけますと幸いです。
(送信された情報は、プライバシーポリシーのもと、厳正に取扱い、処分させていただきます。)

●Pythonのfindメソッドとは?

Pythonには、文字列を操作するための様々なメソッドが用意されています。

その中でも、文字列内の特定の部分文字列を検索するために使用されるのがfindメソッドです。

○Pythonでの文字列操作の基本

Pythonでは、文字列はstr型のオブジェクトとして扱われます。

文字列変数を作成するには、シングルクォート(’)またはダブルクォート(”)で文字列を囲みます。

例えば、message = "Hello, World!"のように記述します。

文字列に対しては、様々なメソッドを適用することができます。

例えば、len()関数で文字列の長さを取得したり、split()メソッドで文字列を分割したりできます。

findメソッドもこうした文字列操作メソッドの1つであり、文字列内の部分文字列の位置を見つけるために使用されます。

○findメソッドの文法とパラメータ

findメソッドは、string.find(substring, start, end)という形式で使用します。

ここで、stringは検索対象の文字列、substringは検索したい部分文字列、startは検索開始位置、endは検索終了位置を表します。

startendは省略可能で、省略した場合はそれぞれ文字列の先頭と末尾が使用されます。

findメソッドは、部分文字列が見つかった場合はその開始位置を返します。部分文字列が見つからない場合は-1を返します。

また、大文字と小文字は区別されるため、検索時には大文字と小文字が一致している必要があります。

では、実際のコード例を見ながら、findメソッドの使い方を詳しく見ていきましょう。

●findメソッドを使った具体的な例

それでは、findメソッドの使い方を具体的なコード例を通して見ていきましょう。

実際のプログラミングシーンでどのように活用されるのか、様々なケースを想定しながら解説します。

○サンプルコード1:単語の位置を見つける

まずは、文章の中から特定の単語の位置を見つける例から始めましょう。

text = "Python is an easy to learn, powerful programming language."
word = "powerful"
position = text.find(word)
print(f"The word '{word}' is found at index {position}.")

実行結果↓

The word 'powerful' is found at index 26.

このコードでは、text変数に文章を格納し、word変数に検索したい単語を指定しています。

そして、find()メソッドを使ってtext内でwordが最初に出現する位置を見つけ、position変数に代入しています。

最後に、print()関数で結果を表示しています。

○サンプルコード2:サブストリングが見つからない場合の処理

次に、検索したい部分文字列が文字列内に存在しない場合の処理方法を見てみましょう。

text = "Python is an easy to learn, powerful programming language."
substring = "java"
position = text.find(substring)
if position == -1:
    print(f"The substring '{substring}' is not found in the text.")
else:
    print(f"The substring '{substring}' is found at index {position}.")

実行結果↓

The substring 'java' is not found in the text.

ここでは、substring変数に検索したい部分文字列を指定しています。

find()メソッドの戻り値が-1の場合、部分文字列が見つからなかったことを意味するので、if文を使って適切なメッセージを表示しています。

○サンプルコード3:大文字と小文字を区別しない検索

デフォルトでは、findメソッドは大文字と小文字を区別して検索を行います。

しかし、大文字と小文字を区別せずに検索したい場合もあるでしょう。

そのような場合は、次のようにします。

text = "Python is an easy to learn, powerful programming language."
substring = "python"
position = text.lower().find(substring.lower())
if position != -1:
    print(f"The substring '{substring}' is found at index {position} (case-insensitive).")
else:
    print(f"The substring '{substring}' is not found in the text (case-insensitive).")

実行結果↓

The substring 'python' is found at index 0 (case-insensitive).

このコードでは、textsubstringの両方をlower()メソッドで小文字に変換してからfind()メソッドを呼び出しています。

これにより、大文字と小文字を区別せずに検索することができます。

○サンプルコード4:文字列内のすべての出現を見つける方法

findメソッドは、部分文字列が最初に出現する位置を返します。

しかし、文字列内で部分文字列がすべて出現する位置を知りたい場合はどうすればよいでしょうか?

その場合は、find()メソッドをループ内で使用することで実現できます。

text = "Python is an easy to learn, powerful programming language. Python is often used for web development, data analysis, artificial intelligence, and more."
substring = "Python"

positions = []
start = 0
while True:
    position = text.find(substring, start)
    if position == -1:
        break
    positions.append(position)
    start = position + 1

if positions:
    print(f"The substring '{substring}' is found at positions: {positions}")
else:
    print(f"The substring '{substring}' is not found in the text.")

実行結果↓

The substring 'Python' is found at positions: [0, 92]

このコードでは、positionsリストを用意し、find()メソッドをwhile文内で繰り返し呼び出しています。

start変数を使って、前回見つかった位置の次の位置から検索を開始するようにしています。

部分文字列が見つかるたびに、その位置をpositionsリストに追加します。

最後に、positionsリストが空でない場合は、部分文字列が見つかった位置を表示します。

○サンプルコード5:テキストファイル内の文字列検索

findメソッドは、文字列変数だけでなく、テキストファイル内の文字列検索にも使用できます。

ここでは、テキストファイルから特定の文字列を検索する例を紹介します。

with open("sample.txt", "r", encoding="utf-8") as file:
    content = file.read()
    substring = "Python"
    position = content.find(substring)
    if position != -1:
        print(f"The substring '{substring}' is found in the file at index {position}.")
    else:
        print(f"The substring '{substring}' is not found in the file.")

実行結果(sample.txtファイルの内容次第)↓

The substring 'Python' is found in the file at index 10.

ここでは、with文を使ってテキストファイル(sample.txt)を開き、read()メソッドを使ってファイルの内容全体をcontent変数に読み込んでいます。

その後、find()メソッドを使ってcontent内で部分文字列を検索し、結果を表示しています。

○サンプルコード6:リスト内の文字列の検索

findメソッドは、リストに格納された文字列の検索にも使用できます。

ここでは、リスト内の各文字列について、特定の部分文字列が含まれているかどうかを確認する例を紹介します。

strings = ["apple", "banana", "cherry", "date", "elderberry"]
substring = "er"
for string in strings:
    if string.find(substring) != -1:
        print(f"The substring '{substring}' is found in '{string}'.")
    else:
        print(f"The substring '{substring}' is not found in '{string}'.")

実行結果↓

The substring 'er' is not found in 'apple'.
The substring 'er' is not found in 'banana'.
The substring 'er' is found in 'cherry'.
The substring 'er' is not found in 'date'.
The substring 'er' is found in 'elderberry'.

このコードでは、stringsリストに複数の文字列を格納し、substring変数に検索したい部分文字列を指定しています。

forループを使ってstringsリストの各要素に対してfind()メソッドを呼び出し、部分文字列が含まれているかどうかを確認しています。

○サンプルコード7:文字列の先頭と末尾からの検索

findメソッドは、文字列の先頭や末尾から特定の文字までの位置を見つけるのにも便利です。

text = "This is a sample text."
first_space = text.find(" ")
last_space = text.rfind(" ")
print(f"The first space is found at index {first_space}.")
print(f"The last space is found at index {last_space}.")

実行結果↓

The first space is found at index 4.
The last space is found at index 15.

ここでは、find()メソッドを使って文字列の先頭から最初のスペースの位置を見つけ、rfind()メソッドを使って文字列の末尾から最後のスペースの位置を見つけています。

rfind()メソッドは、find()メソッドと同様に動作しますが、文字列の末尾から検索を開始します。

○サンプルコード8:複数の異なるサブストリングを検索

文字列内で複数の異なる部分文字列を検索する必要がある場合は、find()メソッドを複数回呼び出すことができます。

text = "Python is an easy to learn, powerful programming language."
substrings = ["easy", "powerful", "programming"]
for substring in substrings:
    position = text.find(substring)
    if position != -1:
        print(f"The substring '{substring}' is found at index {position}.")
    else:
        print(f"The substring '{substring}' is not found in the text.")

実行結果↓

The substring 'easy' is found at index 12.
The substring 'powerful' is found at index 26.
The substring 'programming' is found at index 36.

このコードでは、substringsリストに検索したい部分文字列を複数指定しています。

forループを使って各部分文字列に対してfind()メソッドを呼び出し、その位置を表示しています。

○サンプルコード9:正規表現とfindメソッドの組み合わせ

正規表現を使うことで、より柔軟な文字列検索が可能になります。

reモジュールのsearch()関数と組み合わせることで、正規表現パターンにマッチする部分文字列の位置を見つけることができます。

import re

text = "The price is $10.50."
pattern = r"\$\d+\.\d+"
match = re.search(pattern, text)
if match:
    start = match.start()
    end = match.end()
    print(f"The price is found at index {start} to {end - 1}.")
else:
    print("No price found in the text.")

実行結果↓

The price is found at index 13 to 18.

このコードでは、re.search()関数を使って、正規表現パターン\$\d+\.\d+(ドル記号に続く数字と小数点)にマッチする部分文字列をtext内で検索しています。

マッチが見つかった場合は、start()メソッドとend()メソッドを使ってマッチの開始位置と終了位置を取得し、表示しています。

○サンプルコード10:エラーハンドリングと検索の最適化

文字列検索を行う際には、エラーハンドリングを適切に行い、検索のパフォーマンスを最適化することが重要です。

ここでは、try文を使ったエラーハンドリングと、in演算子を使った検索の最適化の例を紹介します。

def search_substring(text, substring):
    try:
        if substring in text:
            position = text.find(substring)
            print(f"The substring '{substring}' is found at index {position}.")
        else:
            print(f"The substring '{substring}' is not found in the text.")
    except TypeError:
        print("Invalid input. Please provide strings for both text and substring.")

# 使用例
search_substring("Hello, world!", "world")
search_substring("Hello, world!", "python")
search_substring(42, "hello")

実行結果↓

The substring 'world' is found at index 7.
The substring 'python' is not found in the text.
Invalid input. Please provide strings for both text and substring.

ここでは、search_substring()関数を定義し、try文を使ってエラーハンドリングを行っています。

in演算子を使って、部分文字列が文字列内に存在するかどうかを事前にチェックしています。

これにより、部分文字列が存在しない場合にはfind()メソッドを呼び出す必要がなくなり、検索のパフォーマンスが向上します。

また、TypeErrorが発生した場合は、適切なエラーメッセージを表示するようにしています。

●よくあるエラーと対処法

findメソッドを使った文字列検索は非常に便利ですが、時にはエラーに遭遇することがあります。

そのようなエラーに適切に対処し、コードの品質を維持することが重要です。

ここでは、よくあるエラーとその解決策について見ていきましょう。

○TypeError: find() takes at most 3 arguments (4 given)

このエラーは、findメソッドに引数を4つ以上渡した場合に発生します。

findメソッドは最大で3つの引数(検索する文字列、開始位置、終了位置)を受け取ります。

余分な引数を削除するか、必要な引数のみを渡すようにコードを修正しましょう。

text = "Hello, world!"
substring = "world"
start = 0
end = len(text)
position = text.find(substring, start, end)  # 正しい引数の数

○AttributeError: ‘int’ object has no attribute ‘find’

このエラーは、整数オブジェクトに対してfindメソッドを呼び出そうとした場合に発生します。

findメソッドは文字列オブジェクトに対してのみ使用できます。

整数を文字列に変換するか、適切な文字列オブジェクトを使用するようにコードを修正しましょう。

number = 42
position = str(number).find("4")  # 整数を文字列に変換

○ValueError: substring not found

このエラーは、指定した部分文字列が文字列内に見つからない場合に発生します。

部分文字列が存在するかどうかを事前にチェックするか、try-except文を使ってエラーを適切に処理しましょう。

text = "Hello, world!"
substring = "python"
try:
    position = text.find(substring)
    print(f"The substring '{substring}' is found at index {position}.")
except ValueError:
    print(f"The substring '{substring}' is not found in the text.")

●findメソッドの応用例

これまで、findメソッドの基本的な使い方や具体的なコード例を見てきましたが、実際のプログラミングではどのように活用されているのでしょうか?

ここでは、findメソッドのさまざまな応用例を見ていきましょう。

○サンプルコード11:Webスクレイピングでの利用

Webスクレイピングは、ウェブページから情報を抽出する技術ですが、findメソッドはこの分野でも活躍します。

import requests

url = "https://example.com"
response = requests.get(url)
html_content = response.text

keyword = "Python"
if keyword in html_content:
    position = html_content.find(keyword)
    surrounding_text = html_content[position - 20:position + 20]
    print(f"The keyword '{keyword}' is found in the HTML content.")
    print(f"Surrounding text: ...{surrounding_text}...")
else:
    print(f"The keyword '{keyword}' is not found in the HTML content.")

実行結果(例)↓

The keyword 'Python' is found in the HTML content.
Surrounding text: ...earning <strong>Python</strong> programming...

このコードでは、requestsモジュールを使用してウェブページのHTMLコンテンツを取得しています。

そして、find()メソッドを使って、特定のキーワードがHTMLコンテンツ内に存在するかどうかを確認し、キーワードの周辺のテキストを表示しています。

Webスクレイピングでは、HTMLタグや属性値を検索することが多いため、findメソッドは非常に便利です。

ただし、HTMLの構造が複雑な場合は、より強力なツールやライブラリ(BeautifulSoupなど)の使用を検討しましょう。

○サンプルコード12:データ分析でのテキスト処理

データ分析においては、大量のテキストデータを処理することがよくあります。

findメソッドを使って、特定のパターンやキーワードを検索し、関連する情報を抽出することができます。

import pandas as pd

data = [
    {"id": 1, "text": "Python is a versatile language."},
    {"id": 2, "text": "It is easy to learn Python."},
    {"id": 3, "text": "Python has a large community."},
    {"id": 4, "text": "I enjoy coding in Python."}
]

df = pd.DataFrame(data)

keyword = "Python"
df["contains_keyword"] = df["text"].apply(lambda x: keyword in x)
df["keyword_position"] = df["text"].apply(lambda x: x.find(keyword))

print(df)

実行結果↓

   id                              text  contains_keyword  keyword_position
0   1    Python is a versatile language.              True                 0
1   2       It is easy to learn Python.              True                18
2   3    Python has a large community.              True                 0
3   4         I enjoy coding in Python.              True                16

このコードでは、pandasライブラリを使用してデータフレームを作成しています。

そして、apply()メソッドとfind()メソッドを組み合わせて、各テキストにキーワードが含まれているかどうかを判定し、キーワードの位置を取得しています。

データ分析では、テキストデータからパターンや傾向を見つけ出すことが重要です。

findメソッドを活用することで、キーワードの出現頻度や位置を分析し、有益な情報を引き出すことができるでしょう。

○サンプルコード13:自動化スクリプトでの活用

findメソッドは、自動化スクリプトの中でも大活躍します。

ログファイルの解析やエラーメッセージの検出など、さまざまなシナリオで使用できます。

log_file = "application.log"
error_keyword = "ERROR"

with open(log_file, "r") as file:
    for line in file:
        if error_keyword in line:
            error_position = line.find(error_keyword)
            error_message = line[error_position:].strip()
            print(f"Error found: {error_message}")

実行結果(例)↓

Error found: ERROR: Division by zero
Error found: ERROR: File not found

このコードでは、ログファイルを1行ずつ読み込み、各行に”ERROR”というキーワードが含まれているかどうかをfind()メソッドで確認しています。

エラーが見つかった場合は、エラーメッセージを抽出して表示します。

自動化スクリプトでは、大量のテキストデータを処理することが多いため、findメソッドを使って効率的にエラーや重要な情報を見つけ出すことができます。

○サンプルコード14:AIとの組み合わせ

近年、人工知能(AI)の分野では自然言語処理(NLP)が注目を集めています。

findメソッドは、AIアルゴリズムと組み合わせることで、より高度なテキスト解析を行うことができます。

import nltk
from nltk.sentiment import SentimentIntensityAnalyzer

text = "Python is a great programming language. It is easy to learn and has a wide range of applications. However, sometimes it can be slow compared to compiled languages."

sentences = nltk.sent_tokenize(text)
sia = SentimentIntensityAnalyzer()

for sentence in sentences:
    if "Python" in sentence:
        sentiment_scores = sia.polarity_scores(sentence)
        print(f"Sentence: {sentence}")
        print(f"Sentiment scores: {sentiment_scores}")
        print()

実行結果↓

Sentence: Python is a great programming language.
Sentiment scores: {'neg': 0.0, 'neu': 0.508, 'pos': 0.492, 'compound': 0.6249}

Sentence: However, sometimes it can be slow compared to compiled languages.
Sentiment scores: {'neg': 0.13, 'neu': 0.87, 'pos': 0.0, 'compound': -0.2263}

このコードでは、nltkライブラリを使用して、テキストを文単位に分割しています。

そして、各文に”Python”というキーワードが含まれている場合、その文に対して感情分析を行っています。

感情分析では、文の感情(ポジティブ、ネガティブ、ニュートラル)をスコア化することができます。

findメソッドを使って特定のキーワードを含む文を見つけ、その文の感情を分析することで、テキストデータからより深い洞察を得ることができるでしょう。

まとめ

この記事では、Pythonのfindメソッドについて詳しく解説してきました。

findメソッドは、文字列検索において非常に有用です。

この記事で得た知識を活かして、皆さんのプログラミングスキルを磨いていってください。

最後までお読みいただき、ありがとうございました。