Given a strings, determine the number of substrings that satisfy certain criteria. For example we are given a string s="hellohellohello" we need to count how many time the substring occur in the given string suppose we need to find the substring "hello" so that the count becomes 3. We can use methods like count().
s
str.count()
count() method returns the number of non-overlapping occurrences of a substring in the string.
count
()
# Define the input string and the substring to counts="hellohellohello"sub="hello"# Use the count() method to find the number of occurrences of the substringc=s.count(sub)print(c)
3
Explanation:
count()
"hello"
"hellohellohello"
Afor loop can iterate through the string, using slicing to check for the occurrence of a substring. For example, usings[i:i+len(substring)] inside the loop allows for comparing each slice of the string to the target substring
for
s[i:i+len(substring)]
s1="hellohellohello"sub="hello"# Initialize count to zerocnt=0# Iterate through the string to check for the substringforiinrange(len(s)-len(sub)+1):ifs[i:i+len(sub)]==sub:# If substring matches, increment countcnt+=1print(cnt)
substring
Generate a list of indices where the substring starts and count its length.
# Input string and substring to counts="hello world, hello universe"sub="hello"# Count occurrences of the substring using a generator expressionc=sum(1foriinrange(len(s)-len(sub)+1)ifs[i:i+len(sub)]==sub)print(c)
2
sub
G
Python Introduction
Input and Output in Python
Python Variables
Python Operators
Python Keywords
Python Data Types
Conditional Statements in Python
Loops in Python - For, While and Nested Loops
Python Functions
Recursion in Python
Python Lambda Functions
Python String
Python Lists
Python Tuples
Python Dictionary
Python Sets
Python Arrays
List Comprehension in Python
Python OOP Concepts
Python Exception Handling
File Handling in Python
Python Database Tutorial
Python MongoDB Tutorial
Python MySQL
Python Packages
Python Modules
Python DSA Libraries
List of Python GUI Library and Packages
NumPy Tutorial - Python Library
Pandas Tutorial
Matplotlib Tutorial
Python Seaborn Tutorial
StatsModel Library - Tutorial
Learning Model Building in Scikit-learn
TensorFlow Tutorial
PyTorch Tutorial
Flask Tutorial
Django Tutorial | Learn Django Framework
Django ORM - Inserting, Updating & Deleting Data
Templating With Jinja2 in Flask
Django Templates
Python | Build a REST API using Flask
How to Create a basic API using Django Rest Framework ?
Python Quiz
Python Coding Practice
Python Interview Questions and Answers