Python – Remove N characters after K
Last Updated :
24 Mar, 2023
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 : @123 is removed.
Method #1 : Using re.sub()
In this, we specify appropriate regex to capture the element and to remove next N occurrences from String. The sub() is used to perform replacement.
Python3
import re
test_str = 'geeksfor@123geeks is best@212 for cs'
print ( "The original string is : " + str (test_str))
N = 3
K = '@'
res = re.sub(r '\@...' , '', test_str)
print ( "The String after removal : " + str (res))
|
Output
The original string is : geeksfor@123geeks is best@212 for cs
The String after removal : geeksforgeeks is best for cs
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of string.
Method #2 : Using re.sub() + occurrence option
This is similar to above, just using 4th argument of re.sub() to control the occurrence counts we wish to perform replace.
Python3
import re
test_str = 'geeksfor@123geeks is best@212 for cs'
print ( "The original string is : " + str (test_str))
N = 3
K = '@'
res = re.sub(r '\@...' , '', test_str, 1 )
print ( "The String after removal : " + str (res))
|
Output
The original string is : geeksfor@123geeks is best@212 for cs
The String after removal : geeksforgeeks is best@212 for cs
The time and space complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...