Python 文字列 count() と例
⚡ スマートサマリー
Python string count() は、文字列内に特定の文字または部分文字列が何回出現するかを返す組み込みメソッドです。オプションの start および end 引数を使用すると、検索対象をテキストの特定の範囲に限定できます。

何ですか Python 文字列のカウント()?
その カウント() メソッドは組み込み関数です Python 指定された要素が文字列中に何回出現するかを返します。カウントは文字列の先頭から末尾まで行われます。検索を開始する開始インデックスと終了インデックスを指定することもできます。
の構文 Python 文字列カウント()
その Python string count() 関数は、以下の構文を使用します。
string.count(char or substring, start, end)
技術パラメータ
- 文字または部分文字列: 指定された文字列内で検索する単一の文字または部分文字列。count() は、文字列内にその文字または部分文字列が何回出現するかを返します。
- 開始: (オプション)検索を開始する開始インデックスを指定します。指定しない場合は、0から始まります。たとえば、文字列の中央から文字を検索したい場合は、count関数に開始値を指定できます。
- 終わり: (オプション)検索の終了位置を示すインデックスです。指定しない場合は、文字列の末尾まで検索します。たとえば、文字列全体をスキャンするのではなく、検索範囲を特定の位置に限定したい場合は、count 関数に end の値を指定できます。
戻り値
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:指定された文字列内の部分文字列の出現回数をカウントする
次の例は、開始インデックスと終了インデックスを使用して、指定された文字列内で部分文字列が出現する箇所を示しています。
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
Python リストの count() メソッド
count() メソッドは文字列に限定されません。 Python リストとタプルには、特定の要素がシーケンス内に何回出現するかを返す count() メソッドも用意されています。文字列版とは異なり、list.count() と tuple.count() は検索対象の要素のみを受け付け、開始インデックスや終了インデックスの引数は受け付けません。
fruits = ['apple', 'banana', 'apple', 'grape', 'apple']
print(fruits.count('apple')) # counts how many times 'apple' appears
numbers = (1, 2, 2, 3, 2)
print(numbers.count(2)) # count() also works on a tuple
出力:
3 3
count() は文字列とシーケンスの両方に属するため、テキスト内の文字数を数える場合でも、コレクション内の繰り返し項目を数える場合でも、同じメソッド名を使用できます。
重なりを数える方法ping の出来事 Python
count() メソッドは重複しない要素のみをカウントしますping 部分文字列の出現回数をカウントします。一致が重複する場合、count() は予想よりも少ない結果を返します。たとえば、「aaaa」内の「aa」をカウントすると、count() は見つかった一致をスキップするため、3 ではなく 2 を返します。
text = "aaaa"
print(text.count("aa")) # non-overlapping count is 2
import re
overlaps = len(re.findall("(?=(aa))", text))
print(overlaps) # overlapping count is 3
出力:
2 3
重複を数えるping 一致する箇所を見つけるには、re モジュールを先読みアサーションとともに使用するか、find() メソッドでループし、一致する箇所が見つかるたびに検索位置を 1 文字ずつ進めます。
»詳細 Python 文字列メソッド
