How to Count Substrings In a String with Python


In this tutorial, we will introduce the counter function in Python. By using this function, you can easily obtain the number of occurrences of a substring in a string.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

str1 = input('Please input str1: ')
str2 = input('Please input str2: ')

num = str1.count(str2)
print('str2 occurs in str1 for %s times'$num)

Output

Please input str1:  happybirthday
Please input str2:  a
str2 occurs in str1 for 2 times
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments