How to Get the Number of Occurrences of a Substring in Python


In this example we will show how to calculate the frequency of a string occurring in another string using Python.

Source Code

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

str1 = input('please input str1: ')

str2 = input('please input str2: ')

count = str1.count(str2)

print('nstr2 occurs in str1 for %s times'%count)

Output:

please input str1: asdfasta
please input str2: as

str2 occurs in str1 for 2 times

Now we can see that “as” appears 1 time in “asdf”.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments