How to use regex to Remove Last Element from string In Python

Here we are using the concept of regular expression and removing the last character of the string.

Python3




import re
 
def reg(m):
    return m.group(1)
 
# sample string
Str = "w3wiki"
 
# Remove last character from string
new_string = re.sub("(.*)(.{1}$)", reg, Str)
print(new_string)


Output

GEEKSFORGEEK

Python program to Remove Last character from the string

Given a string, the task is to write a Python program to remove the last character from the given string.

Example:

Input:  “w3wiki”
Output: “GeeksForGeek”

Input:  “1234”
Output: “123”
Explanation: Here we are removing the last character of the original string.

Note: Strings are immutable in Python, so any modification in the string will result in the creation of a new string.

Similar Reads

Using list Slicing to Remove the Last Element from the string

The 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....

Using loops and extra space to Remove the Last Element from the string

...

Using rstrip() function to Remove the Last Element from the string

Here we are using some extra space i.e. O(N) and storing all the characters except for the last character....

Using regex to Remove Last Element from string

...

Using list(),pop() and join() methods

The rstrip() is a Python function that returns a string copy after removing the trailing characters....

Using list comprehension and join method

...