Python 文字列 count() と例
Python カウント
count() は組み込み関数です。 Python文字列内の指定された要素の合計数を返します。カウントは文字列の先頭から末尾まで行われます。検索を開始する開始インデックスと終了インデックスを指定することもできます。
の構文 Python文字列カウント()
Python カウント関数の構文:
string.count(char or substring, start, end)
のパラメータ Python 構文
- 文字または部分文字列: 指定した文字列内で検索する単一の文字または部分文字列を指定できます。 指定された文字列内の文字または部分文字列の数を返します。
- start : (オプション) 検索が開始される開始インデックスを示します。 指定しない場合は 0 から始まります。たとえば、文字列の途中から文字を検索したいとします。 count 関数に開始値を与えることができます。
- end: (オプション) 検索が終了する終了インデックスを示します。指定しない場合は、指定されたリストまたは文字列の最後まで検索します。たとえば、文字列全体をスキャンせず、特定のポイントまで検索を制限したい場合は、count 関数で end に値を指定すると、count がそのポイントまで検索します。
戻り値
count() メソッドは、整数値、つまり、指定された文字列からの指定された要素の数を返します。 指定された文字列で値が見つからない場合は 0 を返します。
例 1: 文字列の count メソッド
次の例は、文字列に対する count() 関数の動作を示しています。
str1 = "Hello World" str_count1 = str1.count('o') # counting the character “o” in the givenstring print("The count of 'o' is", str_count1) str_count2 = str1.count('o', 0,5) print("The count of 'o' usingstart/end is", str_count2)
出力:
The count of 'o' is 2 The count of 'o' usingstart/end is 1
例 2: 指定された文字列内の文字の出現をカウントする
次の例では、開始/終了インデックスを使用して、指定された文字列内の文字の出現を示します。
str1 = "Welcome to Guru99 Tutorials!" str_count1 = str1.count('u') # counting the character “u” in the given string print("The count of 'u' is", str_count1) str_count2 = str1.count('u', 6,15) print("The count of 'u' usingstart/end is", str_count2)
出力:
The count of 'u' is 3 The count of 'u' usingstart/end is 2
例 3: 指定された文字列内の部分文字列の出現をカウントする
次の例は、start/endindex を使用した、指定された文字列内の部分文字列の出現を示しています。
str1 = "Welcome to Guru99 - Free Training Tutorials and Videos for IT Courses" str_count1 = str1.count('to') # counting the substring “to” in the givenstring print("The count of 'to' is", str_count1) str_count2 = str1.count('to', 6,15) print("The count of 'to' usingstart/end is", str_count2)
出力:
The count of 'to' is 2 The count of 'to' usingstart/end is 1
まとめ
- count()は組み込み関数です Pythonリストまたは文字列内の指定された要素の数を返します。
- の場合 string、文字列の先頭から最後までカウントが始まります。 検索を開始する開始インデックスと終了インデックスを指定することもできます。
- count() メソッドは整数値を返します。