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]
print(res)
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]
print(res)
Output:
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])
print(res)
Output: Pytho
Using regex function
Import re module for this example.
import re
def second_group(m):
return m.group(1)
name = 'Python'
res = re.sub("(.*)(.{1}$)", second_group, name)
print(res)
Output: Pytho
Do comment if you have any suggestions or doubts on this Python char string topic.
Note: IDE: PyCharm 2021.3.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.