Tuesday, 26 Oct 2021

# Python program to remove last N characters from a string

Python program to remove last N characters from a stringGiven a string S and an integer N, the task is to remove N characters from the end of the string S.Input: S = “GeeksForGeeks”, N = 5Output: GeeksForExplanation: Removing the last 5 characters from “GeeksForGeeks” modifies the string to “GeeksFor”.Input: S = “Welcome”, N = 3Output: WelcApproach 1: Follow the steps below to solve the problem:Below is the implementation of the above approach:Python3  def removeLastN(S, N):            res = ”              for i in range(len(S)-N):                          res += S[i]          return res            S = “GeeksForGeeks”N = 5  print(removeLastN(S, N))Output:
GeeksFor
Time Complexity: O(N), where N is the length of the string.Auxiliary Space: O(N)Approach 2: This problem can be solved using replace(). Follow the steps below to solve the problem:Initialize a string, say res, to store the resultant string.Reverse the string S.Using replace() method, remove the first occurrence of the first N characters of S and store it in res.Reverse the string res.Below is the implementation of the above approach:Python3  def removeLastN(S, N):            res = ”              S = S[::-1]              res = S.replace(S[:N], ”, 1)              res = res[::-1]              return res    S = “GeeksForGeeks”N = 5  print(removeLastN(S, N))Output:
GeeksFor
Time Complexity: O(N), where N is the length of the string.Auxiliary Space: O(N)String slicing-based Approach: Follow the steps below to solve the problem:Initialize a string, say res, to store the resultant string.Update res to S[:len(S) – N], to store all characters except the last N characters of S.Below is the implementation of the above approach:Python3  def removeLastN(S, N):        S = S[:len(S)-N]              return S     S = “GeeksForGeeks”N = 5  print(removeLastN(S, N))Output:
GeeksFor
Time Complexity: O(N), where N is the length of the string.Auxiliary Space: O(1)