工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Python str.count()マスター:文字と部分文字列のカウント実例集

Python str.count()マスター:文字と部分文字列のカウント実例集

str.count()メソッドは、指定した部分文字列が文字列内に何回出現するかを返す軽量な組み込みツールです。単一文字、複数文字パターン、テキストの特定スライス内でのカウントなど、あらゆるニーズに高速かつ正確に対応します。

なぜstr.count()を使うのか

構文概要

string.count(sub[, start[, end]])

パラメータ

戻り値

オプションの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

重要なポイント

Python

  1. Python strip()メソッド完全ガイド:実践例付き
  2. Python format()文字列を明確な例でマスター
  3. Python String.find()メソッド完全ガイド:構文、例、代替手法
  4. Pythonラムダ関数をマスターする:実例とベストプラクティス
  5. Python round()関数を実例で徹底解説
  6. Python map()関数をマスター:構文、例、ベストプラクティス
  7. Python timeit():実行時間測定の実例付きガイド
  8. Python collections.Counter:効率的なカウント、更新、演算操作
  9. Python type()とisinstance()の理解:実例付き解説
  10. Java String.indexOf()マスター:部分文字列検索と実践例
  11. Java String.compareTo()マスター:構文、ユースケース、実践例