Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Master Python’s str.count(): How to Count Characters & Substrings with Examples

Master Python’s str.count(): How to Count Characters & Substrings with Examples

The str.count() method is a lightweight, built‑in tool that returns how many times a specified substring appears in a string. Whether you need to tally single characters, multi‑character patterns, or count within a specific slice of the text, str.count() handles it all with speed and precision.

Why Use str.count()?

Syntax Overview

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

Parameters

Return Value

The method returns an integer indicating the number of non‑overlapping occurrences of sub between the optional start and end indices. If sub isn’t found, it returns 0.

Practical Examples

Example 1: Counting a Single Character

str1 = "Hello World"
print("Count of 'o':", str1.count('o'))
print("Count of 'o' between indices 0 and 5:", str1.count('o', 0, 5))

Output:

Count of 'o': 2
Count of 'o' between indices 0 and 5: 1

Example 2: Counting a Character Across a Phrase

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))

Output:

Count of 'u': 3
Count of 'u' between indices 6 and 15: 2

Example 3: Counting a Substring in a Longer Text

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))

Output:

Count of 'to': 2
Count of 'to' between indices 6 and 15: 1

Key Takeaways

Python

  1. Python Print() Function: A Practical Guide with Examples
  2. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
  3. Master Python `format()` Strings with Clear Examples
  4. Master Python's String.find() Method: Syntax, Examples & Alternatives
  5. Master Python Lambda Functions: Practical Examples & Best Practices
  6. Python round() Function Explained with Practical Examples
  7. Mastering Python's map() Function: Syntax, Examples, and Best Practices
  8. Python timeit() – Measuring Execution Time with Practical Examples
  9. Python list.count(): Expert Guide with Practical Examples
  10. Python Module Importing – A Practical Guide with Examples