Skip to content
Related Articles

Related Articles

Improve Article

Python – Extract string between two substrings

  • Last Updated : 09 May, 2021

Given a string and two substrings, write a Python program to extract the string between the found two substrings. 

Input : test_str = “Gfg is best for geeks and CS”, sub1 = “is”, sub2 = “and” 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Output : best for geeks



Explanation : best for geeks is between is and ‘and’

Input : test_str = “Gfg is best for geeks and CS”, sub1 = “for”, sub2 = “and” 

Output : geeks

Explanation : geeks is between for and ‘and’

Method #1 : Using index() + loop

In this, we get the indices of both the substrings using index(), then a loop is used to iterate within the index to find the required string between them.

Python3




# Python3 code to demonstrate working
# of Extract string between 2 substrings
# Using loop + index()
  
# initializing string
test_str = "Gfg is best for geeks and CS"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing substrings
sub1 = "is"
sub2 = "and"
  
# getting index of substrings
idx1 = test_str.index(sub1)
idx2 = test_str.index(sub2)
  
res = ''
# getting elements in between
for idx in range(idx1 + len(sub1) + 1, idx2):
    res = res + test_str[idx]
  
# printing result
print("The extracted string : " + res)

Output:

The original string is : Gfg is best for geeks and CS
The extracted string : best for geeks 

Method #2 : Using index() + string slicing

Similar to the above method, just the task of slicing is performed using string slicing for providing a much compact solution. 

Python3




# Python3 code to demonstrate working 
# of Extract string between 2 substrings
# Using index() + string slicing
  
# initializing string
test_str = "Gfg is best for geeks and CS"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing substrings
sub1 = "is"
sub2 = "and"
  
# getting index of substrings
idx1 = test_str.index(sub1)
idx2 = test_str.index(sub2)
  
# length of substring 1 is added to
# get string from next character
res = test_str[idx1 + len(sub1) + 1: idx2]
  
# printing result
print("The extracted string : " + res)

Output:

The original string is : Gfg is best for geeks and CS
The extracted string : best for geeks 



My Personal Notes arrow_drop_up
Recommended Articles
Page :