Python – Distance between occurrences

Sometimes, while working with Python Strings, we can have a task in which we need to find the indices difference between occurrences of a particular character. This can have application in domains such as day-day programming. Lets discuss certain ways in which this task can be done.

Method #1 : Using index()
This is one of the way in which we can solve this problem. In this, we use the power of index() to get the Nth index of occurrence and subtract with initial occurrence.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Distance between occurrences
# Using index()
  
# initializing string
test_str = 'geeksforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 'k'
  
# Distance between occurrences
# Using index()
res = test_str.index(K, test_str.index(K) + 1) - test_str.index(K)
  
# printing result 
print("The character occurrence difference is : " + str(res)) 

chevron_right


Output :

The original string is : geeksforgeeks
The character occurrence difference is : 8

 

Method #2 : Using find() + rfind()
The combination of above functions can be used to solve this problem. In this, we find the first occurrence using find() and next(last) using rfind().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Distance between occurrences
# Using find() + rfind()
  
# initializing string
test_str = 'geeksforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K 
K = 'k'
  
# Distance between occurrences
# Using find() + rfind()
res = test_str.rfind(K) - test_str.find(K)
  
# printing result 
print("The character occurrence difference is : " + str(res)) 

chevron_right


Output :

The original string is : geeksforgeeks
The character occurrence difference is : 8



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.