Python indexメソッドで先頭から文字列の位置を検索する

環境
Python 3.9.13
Windows 10 Home 64bit
PyCharm 2022.2.1 (Community Edition)

構文
文字列.index(検索する文字列 )
文字列の先頭から検索し見つかった場合その位置を返します。
先頭は0から始まります。
指定する文字列がない場合ValueErrorを返します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
str1 = 'studyabc'
print(str1.index('s'))
print(str1.index('t'))
print(str1.index('u'))
print(str1.index('stu'))
# coding: utf-8 str1 = 'studyabc' print(str1.index('s')) print(str1.index('t')) print(str1.index('u')) print(str1.index('stu'))
# coding: utf-8

str1 = 'studyabc'
print(str1.index('s'))
print(str1.index('t'))
print(str1.index('u'))
print(str1.index('stu'))

実行結果
0
1
2
0

Python

Posted by arkgame