Python – Extract string between two substrings
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”
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 stringtest_str = "Gfg is best for geeks and CS" # printing original stringprint("The original string is : " + str(test_str)) # initializing substringssub1 = "is"sub2 = "and" # getting index of substringsidx1 = test_str.index(sub1)idx2 = test_str.index(sub2) res = ''# getting elements in betweenfor idx in range(idx1 + len(sub1) + 1, idx2): res = res + test_str[idx] # printing resultprint("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 stringtest_str = "Gfg is best for geeks and CS" # printing original stringprint("The original string is : " + str(test_str)) # initializing substringssub1 = "is"sub2 = "and" # getting index of substringsidx1 = test_str.index(sub1)idx2 = test_str.index(sub2) # length of substring 1 is added to# get string from next characterres = test_str[idx1 + len(sub1) + 1: idx2] # printing resultprint("The extracted string : " + res) |
Output:
The original string is : Gfg is best for geeks and CS The extracted string : best for geeks



