Python – Phrase removal in String
Last Updated :
16 Mar, 2023
Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + enumerate() + list slicing The combination of above methods can be used to solve this problem. In this, we extract the indices of spaces and perform the slicing according to space indices.
Python3
test_str = 'Geeksforgeeks is best for geeks and CS'
print ( "The original string is : " + str (test_str))
K = 2
temp = [idx for idx, ele in enumerate (test_str) if ele = = ' ' ]
res = test_str[temp[K - 1 ]: temp[ - (K - 1 )]].strip()
print ( "String after phrase removal : " + str (res))
|
Output :
The original string is : Geeksforgeeks is best for geeks and CS
String after phrase removal : best for geeks and
Method #2 : Using join() + split() The combination of above methods can be used to perform this task. In this, we split all words and join all the words except the initial and rear K.
Python3
test_str = 'Geeksforgeeks is best for geeks and CS'
print ( "The original string is : " + str (test_str))
K = 2
res = ' ' .join(test_str.split()[K: - (K - 1 )])
print ( "String after phrase removal : " + str (res))
|
Output :
The original string is : Geeksforgeeks is best for geeks and CS
String after phrase removal : best for geeks and
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...