Python Example - Get and remove Last Character from a String
This tutorial explains about following how to examples in Python
- How to get Last character from a String in Python
- Remove last character from a string in python
How to get Last character from a String in Python
First character can be get using index=length-1
One way using find the last index,
- get Length of a string using len(string), substract 1 from given length
- Pass the above index to str such as
str[len(str)-1]
Another way, using negative index This index are iterated from last position of a string. str[-1]
results to last character
str="hello";
print(str[-1]); #0
print(str[len(str)-1]);#0
Remove Last Character from a string in python
Many ways we can remove the last character, return new string
One way by using slicing syntax
str[:-1]
return all characters except first character Next way, find the last index position and str[:lastIndex]
return new string
Second way using rstrip
function
rstrip
removes the last character from a string and return a new string
str="hello";
print(str[:-1]); #hell
lastIndex=len(str)-1
print(str[:lastIndex])#hell
result = str.rstrip(str[-1])
print(result); #hell