Skip to content
Related Articles

Related Articles

Python – Frequency of K in sliced String

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 11 Feb, 2022

Given a String, find frequency of certain character in index range.

Input : test_str = ‘geeksforgeeks is best for geeks’, i = 3, j = 9, K = ‘e’ 
Output : 0 
Explanation : No occurrence of ‘e’ between 4th [s] and 9th element.[e].
Input : test_str = ‘geeksforgeeks is best for geeks’, i = 0, j = 9, K = ‘e’ 
Output : 2 
Explanation : e present as 2nd and 3rd element. 
 

Method #1 : Using slicing and count()

In this, we perform slicing of required string using slice operation, then count() is used to get count of K in that sliced String.

Python3




# Python3 code to demonstrate working of
# Frequency of K in sliced String
# Using slicing + count()
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = 3, 20
 
# initializing K
K = 'e'
 
# slicing String
slc = test_str[i : j]
 
# using count() to get count of K
res = slc.count(K)
 
# printing result
print("The required Frequency : " + str(res))

Output

The original string is : geeksforgeeks is best for geeks
The required Frequency : 3

Method #2 : Using Counter() + slicing 

In this, we perform the task of getting count using Counter(), and slicing is used to perform slice of ranges.

Python3




# Python3 code to demonstrate working of
# Frequency of K in sliced String
# Using Counter() + slicing
from collections import Counter
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = 3, 20
 
# initializing K
K = 'e'
 
# slicing String
slc = test_str[i : j]
 
# Counter() is used to get count
res = Counter(slc)[K]
 
# printing result
print("The required Frequency : " + str(res))

Output

The original string is : geeksforgeeks is best for geeks
The required Frequency : 3


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!