Get Last Character from String
To get the last character from a string in Python, access the character from string using square brackets and pass the index of string length - 1
.
The following expression returns the last character from the string myString
.
myString[len(myString) - 1]
We can also use a negative index of -1
to get the last character from a string.
myString[-1]
ADVERTISEMENT
Examples
In the following program, we take a string in name
variable, and get the last character using square brackets notation.
main.py
name = 'apple' lastChar = name[len(name) - 1] print(f'Last Character : {lastChar}')Try Online
Output
Last Character : e
Now, we shall pass a negative index of -1 in square brackets after the string variable, to get the last character in the string name
.
main.py
name = 'apple' lastChar = name[-1] print(f'Last Character : {lastChar}')Try Online
Output
Last Character : e
Conclusion
In this Python Tutorial, we learned how to get the last character from a string in Python using square brackets notation.