![]() |
Given a string, the task is to write a Python program to remove the last character from the given string. Example:
Note: Strings are immutable in Python, so any modification in the string will result in the creation of a new string. Using list Slicing to Remove the Last Element from the stringThe slicing technique can also remove the last element from the string. str[:-1] will remove the last element except for all elements. Here we are using the concept of slicing and then updating the original string with the updated string. Python3
Output
GeeksForGeek GeeksForGeek Using loops and extra space to Remove the Last Element from the stringHere we are using some extra space i.e. O(N) and storing all the characters except for the last character. Python3
Output
GeeksForGeek Time Complexity: O(n) Using rstrip() function to Remove the Last Element from the stringThe rstrip() is a Python function that returns a string copy after removing the trailing characters. Python3
Output
GeeksForGeek Using regex to Remove Last Element from stringHere we are using the concept of regular expression and removing the last character of the string. Python3
Output
GEEKSFORGEEK Using list(),pop() and join() methodsPython3
Output
GeeksForGeek Using list comprehension and join methodAlgorithm:
Python3
Output
GeeksForGeek Time Complexity: O(n), where n is the length of the input string “Str”. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |