Python str.count()マスター:文字と部分文字列のカウント実例集
Python str.count()マスター:文字と部分文字列のカウント実例集
str.count()メソッドは、指定した部分文字列が文字列内に何回出現するかを返す軽量な組み込みツールです。単一文字、複数文字パターン、テキストの特定スライス内でのカウントなど、あらゆるニーズに高速かつ正確に対応します。
なぜstr.count()を使うのか
- ほとんどのケースでO(n)時間計算量のシンプルさ
- ゼロ依存:外部ライブラリ不要
- 前処理、データ検証、テキストのクイック分析に最適
構文概要
string.count(sub[, start[, end]])
パラメータ
sub– カウントしたい部分文字列または単一文字start(オプション) – 検索開始インデックス。デフォルトは0end(オプション) – 検索終了インデックス (非包含)。デフォルトは文字列長
戻り値
オプションのstartとendインデックスの間で、subの非重複出現回数を示す整数を返します。subが見つからない場合は0を返します。
実践例
例1: 単一文字のカウント
str1 = "Hello World"
print("Count of 'o':", str1.count('o'))
print("Count of 'o' between indices 0 and 5:", str1.count('o', 0, 5))
出力:
Count of 'o': 2 Count of 'o' between indices 0 and 5: 1
例2: フレーズ内の文字カウント
str1 = "Welcome to Guru99 Tutorials!"
print("Count of 'u':", str1.count('u'))
print("Count of 'u' between indices 6 and 15:", str1.count('u', 6, 15))
出力:
Count of 'u': 3 Count of 'u' between indices 6 and 15: 2
例3: 長文での部分文字列カウント
str1 = "Welcome to Guru99 - Free Training Tutorials and Videos for IT Courses"
print("Count of 'to':", str1.count('to'))
print("Count of 'to' between indices 6 and 15:", str1.count('to', 6, 15))
出力:
Count of 'to': 2 Count of 'to' between indices 6 and 15: 1
重要なポイント
str.count()は非重複出現回数を整数で返す- オプションの
startとend引数で特定スライスに検索を限定可能 - Pythonスクリプトでのクイックテキスト分析、データクリーニング、特徴抽出に最適
Python
- Python strip()メソッド完全ガイド:実践例付き
- Python format()文字列を明確な例でマスター
- Python String.find()メソッド完全ガイド:構文、例、代替手法
- Pythonラムダ関数をマスターする:実例とベストプラクティス
- Python round()関数を実例で徹底解説
- Python map()関数をマスター:構文、例、ベストプラクティス
- Python timeit():実行時間測定の実例付きガイド
- Python collections.Counter:効率的なカウント、更新、演算操作
- Python type()とisinstance()の理解:実例付き解説
- Java String.indexOf()マスター:部分文字列検索と実践例
- Java String.compareTo()マスター:構文、ユースケース、実践例