Open In App

Python – Remove after substring in String

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

Given a String, remove all characters after a particular substring.

Input : test_str = ‘geeksforgeeks is best for geeks’, sub_str = “for” 
Output : geeksforgeeks is best for 
Explanation : everything removed after for. 

Input : test_str = ‘geeksforgeeks is best for geeks’, sub_str = “is” 
Output : geeksforgeeks is 
Explanation : everything removed after is.

Method #1 : Using index() + len() + slicing

In this, we first get the index of substring to perform removal after, add to that its length using len() and then slice off elements after that string using slicing.

Python3




# Python3 code to demonstrate working of
# Remove after substring in String
# Using index() + len() + slicing
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing sub string
sub_str = "best"
 
# slicing off after length computation
res = test_str[:test_str.index(sub_str) + len(sub_str)]
 
# printing result
print("The string after removal : " + str(res))


Output

The original string is : geeksforgeeks is best for geeks
The string after removal : geeksforgeeks is best

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of string.

Method #2: Using regex() ( for stripping off after numeric occurrence)

This is a solution to a slightly different problem in which string removal is required after the numeric occurrence. We employ match operation and it retains all before the match is found.

Python3




# Python3 code to demonstrate working of
# Remove after substring in String
# Using regex() ( for stripping off after numeric occurrence)
import re
 
# initializing strings
test_str = 'geeksforgeeks is best 4 geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# slicing after the numeric occurrence
res = re.match(r"(.*\d+)", test_str).group()
 
# printing result
print("The string after removal : " + str(res))


Output

The original string is : geeksforgeeks is best 4 geeks
The string after removal : geeksforgeeks is best 4

Method #3: Using split() method

Algorithm

  1. Initialize an empty list res to hold the resulting substrings.
  2. Initialize a variable start to 0, which represents the starting index of the current substring.
  3. While K is in test_str:
    a. Find the index of the first occurrence of K in test_str, starting from the index start.
    b. Append the substring from start to the index found in step 3a (excluding K) to the list res.
    c. Update start to be the index found in step 3a + the length of K.
    d. Update test_str to be the substring of test_str starting from the index found in step 3a + the length of K.
  4. Append the remaining substring to the list res.
  5. Return the list res

Python3




# Python3 code to demonstrate working of
# Remove after substring in String
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing sub string
sub_str = "best"
 
re = test_str.split(sub_str)
res=re[0]+sub_str
 
# printing result
print("The string after removal : " + str(res))


Output

The original string is : geeksforgeeks is best for geeks
The string after removal : geeksforgeeks is best

The Time and Space Complexity for all the methods are the same:

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

Method#4:Using str.find() and str.slice()

Here is the step-by-step algorithm 

  1. Initialize a string ‘test_str’ with the value “geeksforgeeks is best for geeks”.
  2. Print the original string.
  3. Initialize a substring ‘sub_str’ with the value “best”.
  4. Check if the substring ‘sub_str’ is present in the string ‘test_str’ using the ‘in’ operator.
  5. If the substring is present, find its index in the string using the ‘find()’ method.
  6. Slice the string ‘test_str’ up to the index of the substring plus the length of the substring to remove the portion of the string after the substring.
  7. Store the resulting string in the variable ‘res’.
  8. Print the final string after removing the portion of the string.

Python3




# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing sub string
sub_str = "best"
 
# Remove after substring in String
# Using str.find() and str.slice()
if sub_str in test_str:
    res = test_str[:test_str.find(sub_str) + len(sub_str)]
 
# printing result
print("The string after removal : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original string is : geeksforgeeks is best for geeks
The string after removal : geeksforgeeks is best

The time complexity of the algorithm is O(N), where N is the length of the string ‘test_str’. This is because the ‘find()’ method takes O(N) time in the worst case to find the substring in the string.

The Auxiliary space of the algorithm is O(N), where N is the length of the string ‘test_str’. This is because we are storing the original string ‘test_str’ and the resulting string ‘res’ in memory.

Method#5: reduce() function from the functools module:

Algorithm:

  1. Initialize the input string test_str as ‘geeksforgeeks is best for geeks’.
  2. Initialize the substring sub_str as ‘best’.
  3. Define a function remove_substring(s, sub) that takes two string arguments s and sub and returns a modified string.
  4. In the function remove_substring, find the index of the substring sub in the string s using the find() method.
  5. If the index is not -1, slice the string s up to the index of the substring plus the length of the substring using slicing, and return the modified string.
  6. Otherwise, return the original string s.
  7. Use the reduce() function from the functools module to apply the function remove_substring to the input string test_str and the substring sub_str.
  8. Print the original string test_str and the modified string res.

Python3




# Python3 code to demonstrate working of
# Remove after substring in String
# Using index() + len() + slicing
 
from functools import reduce
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing sub string
sub_str = "best"
 
# define a function to remove the substring and get the result
 
 
def remove_substring(s, sub):
    idx = s.find(sub)
    if idx != -1:
        return s[:idx+len(sub)]
    return s
 
 
# using reduce to apply the function and get the final result
res = reduce(lambda s, sub: remove_substring(s, sub), [sub_str], test_str)
 
# printing result
print("The string after removal : " + str(res))
 
# This code is contributed by Rayudu.


Output

The original string is : geeksforgeeks is best for geeks
The string after removal : geeksforgeeks is best

The time complexity: O(nm), where n is the length of the input string test_str and m is the length of the substring sub_str. This is because the find() method used in the remove_substring() function has a worst-case time complexity of O(n), and it is executed once for each substring in the reduce operation.
Auxiliary space:O(n), as the input string test_str is stored in memory along with the output string res. The remove_substring() function and the lambda function used in the reduce operation do not create any significant additional memory usage.

Method#6: Using replace method:

Algorithm :

  1. Initialize the string test_str with a given value.
  2. Print the original string test_str.
  3. Initialize the substring sub_str with a given value.
  4. Find the index of the sub_str in the test_str.
  5. Remove the portion of the string after the sub_str.
  6. Assign the new string to the variable res.
  7. Print the resulting string.
     

Python3




# initializing strings
 
test_str = 'geeksforgeeks is best for geeks'
 
 
# printing original string
 
print("The original string is : " + str(test_str))
 
 
# initializing sub string
 
sub_str = "best"
 
 
# remove string after sub string
 
res = test_str.replace(test_str[test_str.find(sub_str)+len(sub_str):], '')
 
 
# printing result
 
print("The string after removal : " + str(res))
 
# This code is contributed by Jyothi pinjala.


Output

The original string is : geeksforgeeks is best for geeks
The string after removal : geeksforgeeks is best

Time complexity:  O(n), where n is the length of the string. In this case, finding the index of the sub_str and the length of the sub_str will take O(n) time, and so will the replace function. Therefore, the time complexity of the code is O(n).

Auxiliary Space:  O(n), as we are using variables to store the string values.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads