In this tutorial, learn how to check the last element of a string in Python. The short answer is to use the index operator with -1 as its argument. You may also like to read access string character by index in Python.
How to Check the Last Element of String in Python
If you want to get the last element of the string, you have to use the index operator. You also have to pass the -1 as the argument of the index operator. See the use of the method in the below example prints the last element.
myStr = "refe"
mylastStr = myStr[-1]
print("The last character of string is:", mylastStr)
The above example prints the last item of the string in the output. It finds only the single character from the string. -1 is the argument which you have to use for the last element. 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.
Delete The Last Item of String with Python
If you want to remove the last character of the string, you have to use the index operator. In addition to this, you have to pass
:-1 as the argument of the index operator.
The method first finds the last element from the string. It also deletes the last element of the string. If you print the string after using the method, you will get the string with the deleted element. It will not gives you a single element in the output.
myStr = "refe"
delLastStr = myStr[:-1]
print("String after last element deletion:", delLastStr)
The above example showing the output which contains the string. The string prints without the last element in the output.
You may also like to read
Hope, you like this post of how to check the last element of the string using Python. If you have any query regarding the tutorial, please comment below.
Also tell me, which method you are using to get the last item of string in Python.