Open In App

Python – String till Substring

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, more than finding a substring, we might need to get the string that is occurring before the substring has been found. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using partition() 

The partition function can be used to perform this task in which we just return the part of the partition occurring before the partition word.

Python3




# Python3 code to demonstrate
# String till Substring
# using partition()
 
# initializing string
test_string = "GeeksforGeeks is best for geeks"
 
# initializing split word
spl_word = 'best'
 
# printing original string
print("The original string : " + str(test_string))
 
# printing split string
print("The split string : " + str(spl_word))
 
# using partition()
# String till Substring
res = test_string.partition(spl_word)[0]
 
# print result
print("String before the substring occurrence : " + res)


Output

The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is 

Time Complexity: O(1) as partition() function takes constant time to split the string at the first occurrence of the given substring.
Auxiliary Space: O(1) as we are only using a few extra variables and not creating any new data structures that would increase space complexity.

Method #2 : Using split() 

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 former string. 

Python3




# Python3 code to demonstrate
# String till Substring
# using split()
 
# initializing string
test_string = "GeeksforGeeks is best for geeks"
 
# initializing split word
spl_word = 'best'
 
# printing original string
print("The original string : " + str(test_string))
 
# printing split string
print("The split string : " + str(spl_word))
 
# using split()
# String till Substring
res = test_string.split(spl_word)[0]
 
# print result
print("String before the substring occurrence : " + res)


Output

The original string : GeeksforGeeks is best for geeks
The split string : best
String before the substring occurrence : GeeksforGeeks is 

Time Complexity: O(n), where n is the length of the test_string.

Auxiliary Space: O(1), as we are only using a constant amount of extra space for the variables.

Method #3 : Using find()

Python3




# Python3 code to demonstrate
# String till Substring
# using find()
# you can also use index() instead of find()
 
# initializing string
test_string = "GeeksforGeeks is best for geeks"
 
# initializing substring
spl_word = 'best'
 
# printing original string
print("The original string : " + str(test_string))
 
 
# String till Substring
x=test_string.find(spl_word)
res=test_string[0:x]
 
 
# print result
print("String before the substring occurrence : " + res)


Output

The original string : GeeksforGeeks is best for geeks
String before the substring occurrence : GeeksforGeeks is 

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using Regular Expression (re module)

Python3




import re
 
#initializing string
test_string = "GeeksforGeeks is best for geeks"
 
#initializing substring
spl_word = 'best'
 
#using regular expression
result = re.split(spl_word, test_string, maxsplit=1)[0]
 
#printing result
print("String before the substring occurrence:", result)


Output

String before the substring occurrence: GeeksforGeeks is 

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 5 : using a loop to iterate over the characters of the string.

 step-by-step approach

Initialize the string “test_string” as “GeeksforGeeks is best for geeks”.
Initialize the substring “spl_word” as “best”.
Initialize an empty string “res” to store the characters before the substring occurrence.
Loop over each character “char” in the string “test_string”.
Check if the current character “char” is equal to the first character of the substring “spl_word”.
If the current character is the same as the first character of the substring, check if the substring “spl_word” is found starting from the current index of the string “test_string”.
If the substring is found, break out of the loop.
Otherwise, add the current character “char” to the string “res”.
Once the loop is completed, the string “res” will contain the characters before the first occurrence of the substring “spl_word”.
Print the string “res” as the result.
 

Python3




# Initializing string
test_string = "GeeksforGeeks is best for geeks"
 
# Initializing substring
spl_word = 'best'
 
# Initializing an empty string to store the characters before the substring occurrence
res = ''
 
# Looping over the characters of the string
for char in test_string:
    # Checking if the current character is the first character of the substring
    if char == spl_word[0]:
        # Checking if the substring is found
        if test_string[test_string.index(char):test_string.index(char)+len(spl_word)] == spl_word:
            break
    res += char
 
# Printing the result
print("String before the substring occurrence: " + res)


Output

String before the substring occurrence: GeeksforGeeks is 

The time complexity of this approach is O(n), where n is the length of the string.

 Auxiliary space complexity is O(n), where n is the length of the resulting string.



Similar Reads

Python - Extract String till all occurrence of characters from other string
Given a string, the task is to write a Python program to extract till all characters from other strings are found. Input : test_str = "geeksforgeeks is best for all geeks", check_str = "freak"Output : geeksforgeeks is best for aExplanation : a is last letter in freak to be present in string. The string is printed till first occurrence of a. Input :
11 min read
Python | Repeat String till K
Sometimes, while working with strings, we might encounter a use case in which we need to repeat our string to the size of K, even though the last string might not be complete, but has to stop as the size of string becomes K. The problem of repeating string K times, is comparatively simpler than this problem. Let's discuss way outs we can perform to
4 min read
Python - Extract String till Numeric
Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as 1st letter is numeric. Method #1: Using isdigit()
5 min read
Python program to Extract string till first Non-Alphanumeric character
Given a string, extract all the alphanumerics before 1st occurrence of non-alphanumeric. Input : test_str = 'geek$s4g!!!eeks' Output : geek Explanation : Stopped at $ occurrence. Input : test_str = 'ge)eks4g!!!eeks' Output : ge Explanation : Stopped at ) occurrence. Method #1 : Using regex + search() In this, search() is used to search appropriate
4 min read
Python | Combinations of elements till size N in list
The problem of finding the combinations of list elements of specific size has been discussed. But sometimes, we require more and we wish to have all the combinations of elements of all sizes till N. Let's discuss certain ways in which this function can be performed. Method #1 : Using list comprehension + combinations() This task can be performed us
9 min read
Python program to find the group sum till each K in a list
Given a List, the task is to write a Python program to perform grouping of sum till K occurs. Examples: Input : test_list = [2, 3, 5, 6, 2, 6, 8, 9, 4, 6, 1], K = 6 Output : [10, 6, 2, 6, 21, 6, 1] Explanation : 2 + 3 + 5 = 10, grouped and cumulated before 6. Input : test_list = [2, 3, 5, 6, 2, 6, 8], K = 6 Output : [10, 6, 2, 6, 8] Explanation : 2
3 min read
Python | Prefix Sum Subarray till False value
The prefix array is quite famous in the programming practice. This article would discuss a variation of this scheme. This deals with the cumulative list sum till a False value, and again starts cumulation from the occurrence of True value. Let's discuss certain ways in which this can be performed. Method #1 : Using Naive Method In the naive method,
6 min read
Python | Getting sublist element till N
Sometimes, we may come across a utility in which we require to get the first N sublist elements that too only a particular index. This can have an application in queuing to get only the initial N person's name. Let's discuss certain ways in which this can be done. Method #1: Using list comprehension and list slicing The above two powerful Python ut
4 min read
Python | Get elements till particular element in list
Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let's discuss certain ways in which this task can be performed. Method #1 : Usin
7 min read
Python | Count the elements till first tuple
AuxiliSometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to count the element count that occur before the record. This is a problem that does not occur commonly, but having a solution to it is useful. Let's discuss certain ways in which this task can be performed.
4 min read
Practice Tags :