Home The Quantizer> Python> Python: How to Get the Last Character in a String

Python: How to Get the Last Character in a String

If you are just trying to get the last character of a string in python then here is the quick answer

lastChar = testString[-1]

Here is an example

>>>testString = "stand firm in the faith"
>>>lastChar = testString[-1]
>>>print("The last character of testString is: %s" % lastChar)
The last character of testString is: h

However, there are many other ways to get the last value of as string in python; some may be more useful in your situation than others. Below are several techniques showing how to get the last character and last n characters from a string in Python.

Indexing in Python

There are many ways to get the last character of a string in a Python program. To understand all the following examples we must first understand how indexing in Python works. In Python, you can use the square brackets with a number or a slice notation to tell Python what piece of the string you want to grab. So in the example of “stand firm in the faith” there are 23 total characters. Given the 23 characters, the letter “h” is located at index position 22. Why is the last index in the string 22 and not 23? That is because Python starts counting the first index at 0 making the second character at index 1. One other cool feature of Python is that we can also index in reverse! Just use a negative number starting at -1 to select a character in the string. In the case of the index at -1 Python will select the last index of the string. python string index

>>>testString = "stand firm in the faith"
>>>print("The length of testString is: %d" % len(testString))
The length of testString is: 23

Last character by index

Below is an example of how to use the index to get the last character of a string. However, there are issues with this method of hard coding the index. You have to know the exact index to pull from and if you do not know how long the string is before runtime then this method will not work well. We will describe some better methods next.

>>>testString = "stand firm in the faith"
>>>lastChar = testString[22]
>>>print("The last character of testString is: %s" % lastChar)
The last character of testString is: h

Last character using the len() function

A more deterministic way of getting the last index in a string is by using len() function to get the length of the string. The len() function in this case will return 23, so we need to subtract one from the length to get the value at index position 22. This will get the last character of a string every time! This way works well but the next way we will show you is my preferred method to grab the last character of a string.

>>>testString = "stand firm in the faith"
>>>lastChar = testString[len(testString)-1]
>>>print("The last character of testString is: %s" % lastChar)
The last character of testString is: h

Last character using negative indexes

Probably the easiest way to get the last character of a Python string is to use negative indexing. Using negative numbers for an index in Python will start at the end of a string and count towards the beginning. So given a string “stand firm in the faith” if you just want “h”, the last character of the string, then use an index of -1 to get it. The following example shows how to use negative indexes

>>>testString = "stand firm in the faith"
>>>lastChar = testString[-1]
>>>print("The last character of testString is: %s" % lastChar)
The last character of testString is: h

Caution when dealing with an empty string

All the methods in the above code have the potential of throwing an exception if we do not put some error checking in the program. In this example, instead of using our original strings we tested with we will create a new string that does not have any characters in it. The below code shows that if we try to read from any index number of the string Python will then throw an exception.

>>>sampleString = ""
>>>lastChar = sampleString[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

The easy way to fix the above example is by putting in a check to make sure our sample string has a non-zero list of characters in it

>>> testString = ""
>>> if len(testString) > 0:
...  lastChar = testString[len(testString) - 1]
...  print("The last character of testString is: %s" % lastChar)
... else:
...  print("The string was empty")
The string was empty

That is it, regardless if you are trying grab the first character of the string or any of the last characters of a string it is important to verify the index will exist so that an exception is not thrown

Last n characters of a string

Another one of the different ways available is to grab a set of characters. To do this we will use what Python calls a slice operator :. A slice operator is a type of notation that tells the language what index to start at and what index to stop at. In Python the first number of the slice is the start and the last number is where python stops slicing exclusively. This is important to pay attention to the inclusive start index and the exclusive end index. If you are getting one too many or too few characters with a slice it is probably because of a misunderstanding in how it is used. Also, with a slice if you do not specify the start or stop index than Python will go all the way to the beginning or end of the string, respectively.

>>>testString = "stand firm in the faith"
>>>extractedString = testString[6:10]
>>>print("Extracted string: %s" % extractedString)
Extracted string: firm

Last n characters using string slicing

To get the last n characters using a slice just select the start and stop index. For example if we want to get the last word of our test string “stand firm in the faith” we would use the starting index of 18 and end at the end of the string using the slice operator

>>>testString = "stand firm in the faith"
>>>lastChars = testString[18:]
>>>print("The last five character of testString is: %s" % lastChars)
The last five character of testString is: faith

Additionally, we could use a slightly better way of doing the same thing by using the len() function and subtracting 6

  • -6 because
    • -1 because of indexing starts at zero
    • -5 for the last five characters we are trying to get
>>>testString = "stand firm in the faith"
>>>lastChars = testString[len(testString)-6:]
>>>print("The last five character of testString is: %s" % lastChars)
The last five character of testString is: faith

Last n characters using slices and negative indexing

This one is a little strange, but it may be just what you are looking for. You can use negative indexing to specify the start index and then do not specify the end index to grab the rest of the string.

>>>testString = "stand firm in the faith"
>>>lastChars = testString[-5:]
>>>print("The last five character of testString is: %s" % lastChars)
The last five character of testString is: faith

Last word in a string

If you are dealing with sentences and are trying to get the last word of a string the best thing to do is use some string manipulation to split up the original string into an array of new strings by using the split() function. The first arugument of the split function indicates the specific character to split the given string on. When specifying what character to split on it can be any of the unicode characters, even special characters. In our case we want to split on the space character ‘ ‘. Then all we have to do is pick one of the techniques listed above to grab the last word. In this case we will show the negative indexing technique.

>>>testString = "stand firm in the faith"
>>>>words = testString.split(" ")
>>>print("The last word of testString is: %s" % words[-1])
The last word of testString is: faith

Caution when dealing with an empty string

This is less risky than accessing the index of the last element of the string because the split function will return an array with the contents [’’] in it so an exception will not be thrown. However, it is still good practice to add error handling so that unexpected behavior further down in the program does not occur

>>>sampleString = ""
>>>testString = ""
>>>words = testString.split(' ')
>>>print(words)
['']
>>>print print("The last word of testString is: %s" % words[-1])
The last word of testString is:

There is no error but this is probably not the result our code is expecting. The fix it is similar to the previous error checking example

>>>testString = ""
>>>if testString.count(" ") > 0:
>>>    words = testString.split(' ')
>>>    print("The last word of testString is: %s" % words[-1])
>>>else:
>>>    print("There was not multiple words in the string")
There was not multiple words in the string

So regardless if you are checking for the first n characters of a string or the last n characters of the string it is important to make sure at least n number of characters exist.

Removing whitespace from a string

It may be that you are trying to get the last character of a string to see if the individual characters are printable character or a white space character. Instead of writing out that evaluation you can use the one of the built-in string methods. In this example we are going to show how to use the strip() method.

>>>testString = "this string has white space on the end  "
>>>print("[%s]" % testString)
[this string has white space on the end  ]
>>>testString = testString.strip()
>>>print("[%s]" % testString)
[this string has white space on the end]

As you can see the strip method removed the whitespace from the end of the string. So if all you were trying to do was get the last character to see if you needed to remove any white space then the strip method is a much easier way of achieving the same goal.

©  The Quantizer