Python 文字列内の特定の文字の位置を検索

Document 对象参考手册Python3 実例

Python では、find()メソッドを使用して、文字列内の特定の文字の位置を検索できます。find()このメソッドは、その文字が文字列内で最初に出現するインデックス位置を返します。文字が存在しない場合は -1 を返します。

実例

# 文字列を定義する
text = "Hello, welcome to the world of Python."

# 文字 'w' の位置を検索する
position = text.find('w')

# 結果を出力する
print("The position of 'w' is:", position)

コードの解説:

  • text = "Hello, welcome to the world of Python.":文字列を定義しますtext。
  • position = text.find('w'):使用find()メソッドで文字'w'の文字列内のtext位置を検索し、その結果を変数positionに格納します。
  • print("The position of 'w' is:", position):文字'w'の位置を出力します。

出力結果:

The position of 'w' is: 7

この例では、文字'w'の文字列内のインデックス位置は 7 です。

Document 对象参考手册Python3 実例

その他の拡張