Python – Slice from Last Occurrence of K
Last Updated :
23 Apr, 2023
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the task of performing characters stripping on the last occurrence of element. This can have applications in which data is involved. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + string slicing The combination of above methods can be used to solve this problem. In this, we search for the last occurrence using loop and save index to later slice.
Python3
test_str = 'geeksforgeeks-is-best-for-geeks'
print ( "The original string is : " + str (test_str))
K = "-"
idx = None
for i in range ( len (test_str)):
if K = = test_str[i]:
idx = i
res = test_str[:idx]
print ( "Sliced String is : " + str (res))
|
Output :
The original string is : geeksforgeeks-is-best-for-geeks
Sliced String is : geeksforgeeks-is-best-for
Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(n)
Method #2: Using rfind() + string slicing The combination of above methods can be used to solve this problem. In this, we extract the last occurrence using rfind() and rest slicing as above method.
Python3
test_str = 'geeksforgeeks-is-best-for-geeks'
print ( "The original string is : " + str (test_str))
K = "-"
idx = test_str.rfind(K)
res = test_str[:idx]
print ( "Sliced String is : " + str (res))
|
Output :
The original string is : geeksforgeeks-is-best-for-geeks
Sliced String is : geeksforgeeks-is-best-for
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using max() method
Python3
test_str = 'geeksforgeeks-is-best-for-geeks'
print ( "The original string is : " + str (test_str))
K = "-"
x = []
res = []
for i in range ( 0 , len (test_str)):
if (test_str[i] = = K):
x.append(i)
res = test_str[: max (x)]
print ( "Sliced String is : " + str (res))
|
Output
The original string is : geeksforgeeks-is-best-for-geeks
Sliced String is : geeksforgeeks-is-best-for
Time complexity : O(n), where n is length of test_str
Auxiliary space : O(n), where n is length of res string.
Method#4: Using split() and join()
this approach involves splitting the input string using the separator K, joining all the parts except the last one using the same separator K, and returning the joined string.
Algorithm
1. Split the string using K as the separator.
2. Join all the parts except the last one using K as the separator.
3. Return the joined string.
Python3
def slice_last_occurrence(test_str, K):
parts = test_str.split(K)
sliced_str = K.join(parts[: - 1 ])
return sliced_str
test_str = 'geeksforgeeks-is-best-for-geeks'
K = "-"
print (slice_last_occurrence(test_str, K))
|
Output
geeksforgeeks-is-best-for
Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is length of string
Share your thoughts in the comments
Please Login to comment...