How To Get The Last N Characters Of A String In Python

Introduction

 
In this article, you will  learn about 3 different ways of printing the last N character from a String in Python.
 

Python

 
Python is an interpreted, high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. He started Python as a hobby project to keep him occupied in the week around Christmas. It got its name from the name of British comedy troupe Monty Python. It is used in :
  1. Software Development
  2. Web Development
  3. System Scripting
  4. Mathematics
To learn how to program in Python, visit Python Basics.
 

Python String

 
String is an array of bytes that represent the Unicode characters in Python. Python does not support character datatype. A single character also works as a string. Python supports writing the string within a single quote('') and a double quote("").
 
To read more about Python String, visit

Finding the last N characters of a String

 
To understand the concepts, I will take a demo string "C# Corner". The given string is represented in memory in the following manner:
 
python_slicing
 

String Slicing

 
Slicing means to chop off anything, and string slicing means to extarct the desired part of string and print it. Given below is the memory representation of the demo string along with the index values.
 
 
The indexes from 0 to 4 are called positive indexes or the default indexes. Positive Indexes always started from zero.
 
The indexes from -5 to -1 are called the negative indexes. Negative Indexes always start from -1 and go up to the lower limit; i.e. minus the length of the string plus 1 i.e. "-(len(string)+1)". Negative indexes are used to fetch a string in reverse order.
 

To print the last character of a String

 
slicing
 

Method 1: Using Negative Slicing a String

 
In this method we will use negative slicing i.e. we will be printing the value stored at the -1 index of the demo string.
  1. str = "C# Corner"    
  2. print(str[-1])
Output will be: r
 
Another way to print the last element of a string is
  1. str = "C# Corner"        
  2. print(str[-1::])    # or print(str[-1:]) 
Similarly, we can print the last 2 elements by the following logic
  1. str = "C# Corner"      
  2. print(str[-2::]) # or print(str[-2:])
Output will be: er
 
In the same way, you can print N last characters of a String.
 

Method 2: Using Reverse a String

 
This involves reversing a string and then using positive slicing. To understand the method let us first see what are the various ways to reverse a string.
 
1. Using String slicing
  1. string = "C# Corner"  
  2.     
  3. print ("The original string  is : ",end="")   
  4. print (string)   
  5.     
  6. print ("The reversed string(using loops) is : ",end="")   
  7. print (string[::-1]) 
In the above code, we use the concept of slicing, where "string[::-1]" means that we have to print the whole string starting from the "negative one" index.
 
2. Using Loops
  1. def reverse(s):   
  2.   _str = ""   
  3.   for i in s:   
  4.     _str = i + _str 
  5.   return _str 
  6.     
  7. string = "C# Corner"  
  8.     
  9. print ("The original string  is : ",end="")   
  10. print (string)   
  11.     
  12. print ("The reversed string(using loops) is : ",end="")   
  13. print (reverse(string))  
In the above code, we use the concept that we generally use with the palindrome checking. Here we take an empty string and start adding each character one by one starting from the last character.
 
3. Using Recursion
  1. def reverse(s):   
  2.     if len(s) == 0:   
  3.         return s   
  4.     else:   
  5.         return reverse(s[1:]) + s[0]   
  6.     
  7. _str = "C# Corner"  
  8.     
  9. print ("The original string  is : ",end="")   
  10. print (_str)   
  11.     
  12. print ("The reversed string(using recursion) is : ",end="")  
  13. print (reverse(_str))  
In the above code, we use the concept of recursion to print all characters one by one starting from the last character.
 
4. Using "reversed"
  1. def reverse(string):   
  2.     string = "".join(reversed(string))   
  3.     return string   
  4.     
  5. _str = "C# Corner"  
  6.     
  7. print ("The original string  is : ",end="")   
  8. print (_str)   
  9.     
  10. print ("The reversed string(using reversed) is : ",end="")  
  11. print (reverse(_str))  
In the above code, we use the string "join()" method, which performs string concatenation, and reversed() is used to return the reversed iterator of the given sequence.
 
You can use any of the above methods to reverse the string, I have used the string slicing method to reverse the string.
 
In the below code, we reverse the string and then print the index zero of the reversed string.
  1. str = "C# Corner"  
  2. print(str[::-1][0])  # or print(str[::-1][0:1]) 
Output will be: r
 
Similarly to print the last 2 characters of the string we can do the following:
  1. str = "C# Corner"  
  2. print(str[::-1][0:2]) 
Output will be: re
 
In the same way, you can print the last N characters of a String.
 

Method 3: Using the length of the string

 
In this method, we will first find the length of the string and then we will print the last N characters of the string.
  1. _str = "C# Corner"  
  2. print(_str[len(_str)-1]) 
In the above code, we print the last character of the string by printing the length minus 1 value of the string.
  1. _str = "C# Corner"  
  2. N_of_char = 2  
  3. for i in range(0,N_of_char):  
  4.     print(_str[len(_str)-(i+1)],end="") 
You can use the above example to print any number of last characters, you just need to change the "N_of_char" value to your desired value. I wanted to print the last 2 characters, so I have set that value to 2.
 

Conclusion

 
In this article, we discussed 3 ways of printing the last N characters of a String in Python. Do try out these ways and comment with your views on how useful this article was.
 
Visit C# Corner to find answers to more such questions.
 
If you have any questions regarding any other technology do have a look at the C# Corner Technology Page.