pythonコード百科事典

コピペですぐ使えるPythonコードをご紹介

Pythonで文字列を比較する方法(部分一致)

Pythonには、文字列の部分一致を比較するための様々な方法があります。

in 演算子を使う

文字列 s の中に、文字列 t が含まれているかどうかを調べるには、以下のように in 演算子を使います:

if t in s:
    print("t is a substring of s")
else:
    print("t is not a substring of s")

str.find() メソッドを使う

str.find() メソッドは以下のように使います:

if s.find(t) != -1:
    print("t is a substring of s")
else:
    print("t is not a substring of s")

str.index() メソッドを使う

str.index() メソッドは以下のように使います:

try:
    s.index(t)
    print("t is a substring of s")
except ValueError:
    print("t is not a substring of s")

re モジュールを使う

re モジュールは以下のように使います:

import re

if re.search(t, s):
    print("t is a substring of s")
else:
    print("t is not a substring of s")

上記の方法の中で、好みや使用シーンに応じて、最適なものを選択することができます。