Python string delete last character | Example code

  • by

Use slicing or rstrip() method to delete the last character of string in Python. You can also use regular expression or loop for it but it is not required because in-build methods can do that same task.

Python string delete the last character Example

Simple example code.

Using Slicing

The index -1 gets you the last element from the iterable. Negative index by slicing.

name = 'Python'
res = name[:-1]

Or calculated the length of the string to access the last character of the string. Positive index by slicing.

name = 'Python'
l = len(name)
res = name[:l - 1]



Python string delete last character

Using rstrip

The string method rstrip is used to remove the characters from the right side of the string that is given to it.

name = 'Python'
res = name.rstrip(name[-1])


Output: Pytho

Using regex function

Import re module for this example.

import re

def second_group(m):

name = 'Python'
res = re.sub("(.*)(.{1}$)", second_group, name)


Output: Pytho

Do comment if you have any suggestions or doubts on this Python char string topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.