Last Updated on May 16, 2024 by Roshan Parihar
To get the last character of a string in Python, use the index operator ([]) with -1
as its argument. -1 is the index position of the last character of every string.
How to Get the Last Character of String in Python
If you want to get the last character of the string, you have to use the index operator ([]
). You also have to pass the -1
as the argument of the index operator for getting the last character.
Example 1: Get last character of string
1 2 3 |
myStr = "refe" mylastStr = myStr[-1] print("The last character of string is:", mylastStr) |
Output
The above example prints the last character of the string in the output. However, this method does not remove the last element with the above method. You have to use the below method given in the below section.
Get Last n Characters of String in Python
If you want to get the last n characters of a string in Python, you can use the index operator ([]
) and pass the argument as -n:
. You have to replace the n
with your number of characters to get from the string>
Example 2: Get last 2 characters of string
1 2 3 |
myStr = "qwertyuiop" mylastStr = myStr[-2:] print("The last 2 characters of string are:", mylastStr) |
Output
More Examples to Get More Characters
Example 3: Get last 3 characters of string
1 2 3 |
myStr = "qwertyuiop" mylastStr = myStr[-3:] print("The last 3 characters of string are:", mylastStr) |
Output
Example 4: Get last 4 characters of string
1 2 3 |
myStr = "qwertyuiop" mylastStr = myStr[-4:] print("The last 4 characters of string are:", mylastStr) |
Output
You may also like to read