Python | Get the string after occurrence of given substring
Last Updated :
26 Mar, 2023
Sometimes, more than finding a substring, we might need to get the string that is occurring after the substring has been found. Let’s discuss certain ways in which this task can be performed using Python.
Using partition() to get string after occurrence of given substring
The partition function can be used to perform this task in which we just return the part of partition occurring after the partition word.
Python3
test_string = "GeeksforGeeks is best for geeks"
spl_word = 'best'
print ( "The original string : " + str (test_string))
print ( "The split string : " + str (spl_word))
res = test_string.split(spl_word, 1 )
splitString = res[ 1 ]
print ( "String after the substring occurrence : " + splitString)
|
Output
The original string : GeeksforGeeks is best for geeks
The split string : best
String after the substring occurrence : for geeks
Using split() to get string after occurrence of given substring
The split function can also be applied to perform this particular task, in this function, we use the power of limiting the split and then print the later string.
Python3
test_string = "GeeksforGeeks is best for geeks"
spl_word = 'best'
print ( "The original string : " + str (test_string))
print ( "The split string : " + str (spl_word))
res = test_string.split(spl_word, 1 )
print ( "String after the substring occurrence : " + res[ 1 ])
|
Output :
The original string : GeeksforGeeks is best for geeks
The split string : best
String after the substring occurrence : for geeks
Using find() method
Python3
test_string = "GeeksforGeeks is best for geeks"
spl_word = 'best'
print ( "The original string : " + str (test_string))
print ( "The split string : " + str (spl_word))
res = test_string[test_string.find(spl_word) + len (spl_word):]
print ( "String after the substring occurrence : " + res)
|
Output
The original string : GeeksforGeeks is best for geeks
The split string : best
String after the substring occurrence : for geeks
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of string.
Using re to get string after occurrence of given substring:
This approach uses a regular expression to search for the first occurrence of the substring in the input string, and returns the portion of the string after the substring if it is found. If the substring is not found, an empty string is returned.
Python3
import re
test_string = "GeeksforGeeks is best for geeks"
spl_word = 'best'
match = re.search(spl_word, test_string)
if match:
res = test_string[match.end():]
else :
res = ''
print ( "String after the first occurrence of substring:" , res)
|
Output
String after the first occurrence of substring: for geeks
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1), as no additional data structures are used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...