Skip to content
Related Articles

Related Articles

Python – Remove after substring in String

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Aug, 2022
View Discussion
Improve Article
Save Article

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

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

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)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!