Python 文字列内の部分文字列の位置を検索する
Python では、次を使用できますfind()メソッドを使用して、文字列内の部分文字列の位置を検索します。部分文字列が見つかった場合、find()メソッドは部分文字列が最初に現れるインデックスを返します。見つからない場合は -1 を返します。
例
# 文字列を定義する
text = "Hello, welcome to the world of Python."
# 部分文字列 "welcome" の位置を検索
position = text.find("welcome")
# 結果を出力
print("部分文字列の位置:", position)
text = "Hello, welcome to the world of Python."
# 部分文字列 "welcome" の位置を検索
position = text.find("welcome")
# 結果を出力
print("部分文字列の位置:", position)
コードの説明:
text = "Hello, welcome to the world of Python.":文字列を定義するtext。position = text.find("welcome"):使用find()メソッドで部分文字列を検索"welcome"にtext内の位置を検索し、結果を変数に格納positionする。print("子字符串的位置是:", position):部分文字列の位置を出力する。
出力結果:
子字符串的位置是: 7
この例では、部分文字列"welcome"は文字列text内の開始位置はインデックス 7 です。
Python3 実例