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.



Similar Reads

Python | Get the string after occurrence of given substring
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 retu
3 min read
Python | Remove the given substring from end of string
Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Remove the substring from the end of the string using Slicing In this method, we are using string slicing to remove th
3 min read
Python | Remove substring list from String
Sometimes, while working with Python Strings, we can have a problem in which we need to remove a substring from the String. This is quite easy and many times solved before. But sometimes, we deal with a list of strings that need to be removed and String adjusted accordingly. Let's discuss certain ways in which this task is achieved. Example Input:
7 min read
Python - Remove keys with substring values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove keys whose values have substring as argument we pass. This problem can occur in cases of web development and day-day programming. Lets discuss certain ways in which this task can be performed. Input : test_dict = {1 : 'Gfg is best for geeks'} sub_lis
6 min read
Python - Remove N characters after K
Given a String, remove N characters after K character. Input : test_str = 'ge@987eksfor@123geeks is best@212 for cs', N = 3, K = '@' Output : 'geeksforgeeks is best for cs' Explanation : All 3 required occurrences removed. Input : test_str = 'geeksfor@123geeks is best for cs', N = 3, K = '@' Output : 'geeksforgeeks is best for cs' Explanation : @12
2 min read
Python - Remove front K characters from each string in String List
Sometimes, we come across an issue in which we require to delete the first K characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in which this can
6 min read
Python - Remove String from String List
This particular article is indeed a very useful one for Machine Learning enthusiast as it solves a good problem for them. In Machine Learning we generally encounter this issue of getting a particular string in huge amount of data and handling that sometimes becomes a tedious task. Lets discuss certain way outs to solve this problem. Method #1: Usin
4 min read
Python | Check if substring present in string
Let us solve this general problem of finding if a particular piece of string is present in a larger string in different ways. This is a very common kind of problem every programmer comes across atleast once in his/her lifetime. This article gives various techniques to solve it. Method 1: Using in operator The in operator is the most generic, fastes
5 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more. Syntax of list slicin
4 min read
Python | Frequency of substring in given string
Finding a substring in a string has been dealt with in many ways. But sometimes, we are just interested to know how many times a particular substring occurs in a string. Let's discuss certain ways in which this task is performed. Method #1: Using count() This is a quite straightforward method in which this task is performed. It simply counts the oc
6 min read
Practice Tags :
three90RightbarBannerImg