Python – Slice from Last Occurrence of K
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
# Python3 code to demonstrate working of# Slice from Last Occurrence of K# Using string slicing and loop# initializing stringtest_str = 'geeksforgeeks-is-best-for-geeks'# printing original stringprint("The original string is : " + str(test_str))# initializing KK = "-"# Slice from Last Occurrence of K# Using string slicing and loopidx = Nonefor i in range(len(test_str)): if K == test_str[i]: idx = ires = test_str[:idx]# printing resultprint("Sliced String is : " + str(res)) |
The original string is : geeksforgeeks-is-best-for-geeks Sliced String is : geeksforgeeks-is-best-for
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
# Python3 code to demonstrate working of# Slice from Last Occurrence of K# Using rfind() + string slicing# initializing stringtest_str = 'geeksforgeeks-is-best-for-geeks'# printing original stringprint("The original string is : " + str(test_str))# initializing KK = "-"# Slice from Last Occurrence of K# Using rfind() + string slicingidx = test_str.rfind(K)res = test_str[:idx]# printing resultprint("Sliced String is : " + str(res)) |
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)
Space Complexity: O(n)


