In this article, we will discuss how to fetch the last N characters of a string in python. This N can be 1 or 4 etc.
In python, a String is a sequence of characters, and each character in it has an index number associated with it. For example, we have a string variable sample_str that contains a string i.e.
sample_str = "Sample String"
Each character in this string has a sequence number, and it starts with 0 i.e.
‘S’ has index 0
‘a’ has index 1
‘m’ has index 2
‘p’ has index 3
‘l’ has index 4
‘e’ has index 5
‘ ‘ has index 6
‘S’ has index 7
‘t’ has index 8
‘r’ has index 9
‘i’ has index 10
‘n’ has index 11
‘g’ has index 12
In python String provides an [] operator to access any character in the string by index position. We need to pass the index position in the square brackets, and it will return the character at that index. This index position can be a positive or negative int value.
Like sample_str[i] will return a character at index i-th index position. We used the same concept to access the first N characters of a string in the previous article.
But here, the situation is a little tricky; we want to access the elements from last in the string. Well, there are different ways to do this, let’s discuss them one by one.
Use Negative indexing to get the last character of a string in python
Apart from positive indexes, we can pass the -ve indexes to in the [] operator of string. Each character in the string has a negative index associated with it like last character in string has index -1 and second last character in string has index -2.
So, if our string is ‘Sample String’ the negative indexing in it will be like,
‘S’ has index -13
‘a’ has index -12
‘m’ has index -11
‘p’ has index -10
‘l’ has index -9
‘e’ has index -8
‘ ‘ has index -7
‘S’ has index -6
‘t’ has index -5
‘r’ has index -4
‘i’ has index -3
‘n’ has index -2
‘g’ has index -1
The last character of a string has index position -1. So, to get the last character from a string, pass -1 in the square brackets i.e.
# Get last character of string i.e. char at index position -1 last_char = sample_str[-1] print('Last character : ', last_char)
Output:
Last character : g
It returned a copy of the last character in the string. You can use it to check its content or print it etc.
Get the last character of string using len() function
If we don’t want to use the negative indexing, then we can sill access the last character of string by calculating its length first and then access character at length -1
# get the length of string length = len(sample_str) # Get last character of string i.e. char at index position len -1 last_char = sample_str[length -1] print('Last character : ', last_char)
Output:
Last character : g
But this is a little heavy solution as compared to the previous one.
In the above example, we fetched the last character or the string using different techniques, but what if we want more like, get the last four characters of a string, etc. Basically we want to access a substring of given length from the end of the string. How to do that?
Get last N characters in a string
In python, apart from index position, subscript operator, i.e. [] can accept a range too i.e.
string[ start_index_pos: end_index_pos: step_size]
It returns a slice the string, i.e. a substring. If we want to get more than one character out of a string i.e. fetch a substring, then we can pass these range elements in [] operator,
- start_index_pos: Index position, from where it will start fetching the characters, the default value is 0
- end_index_pos: Index position till which it will fetch the characters from string, default value is the end of string
- step_size: Interval between each character, default value is 1.
To get the last N characters of the string, we need to either pass negative indexes or use len() function to calculate the range,
Get last four characters of a string in python using negative indexes
sample_str = "Sample String" # Get last 3 character last_chars = sample_str[-3:] print('Last 3 character : ', last_chars)
Output:
Last 3 character : ing
We sliced the string from fourth last the index position to last index position and we got a substring containing the last four characters of the string.
Get last four characters of a string in python using len() function
# get the length of string length = len(sample_str) # Get last 3 character last_chars = sample_str[length - 3 :] print('Last 3 character : ', last_chars)
Output:
Last 4 character : ring
We calculated the length of the string first, then sliced the string from (length – 4) index position to the last index position and we got a substring containing the last four characters of the string.
The complete example is as follows,
def main(): sample_str = "Sample String" print('**** Get last character of a String in python ****') # Get last character of string i.e. char at index position -1 last_char = sample_str[-1] print('Last character : ', last_char) print('** Get the last character of string using len() function **') # get the length of string length = len(sample_str) # Get last character of string i.e. char at index position len -1 last_char = sample_str[length -1] print('Last character : ', last_char) print('**** Get the last N characters of string using negative indexes ****') # Get last 3 character last_chars = sample_str[-3:] print('Last 3 character : ', last_chars) print('**** Get the last N characters of string using len() function ****') # get the length of string length = len(sample_str) # Get last 3 character last_chars = sample_str[length - 3 :] print('Last 3 character : ', last_chars) if __name__ == '__main__': main()
Output:
**** Get last character of a String in python **** Last character : g ** Get the last character of string using len() function ** Last character : g **** Get the last N characters of string using negative indexes **** Last 3 character : ing **** Get the last N characters of string using len() function **** Last 3 character : ing
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.