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.

str = "C# Corner"    
print(str[-1])

Output will be: r

Another way to print the last element of a string is

str = "C# Corner"        
print(str[-1::])    # or print(str[-1:]) 

Similarly, we can print the last 2 elements by the following logic

str = "C# Corner"      
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

string = "C# Corner"  
    
print ("The original string  is : ",end="")   
print (string)   
    
print ("The reversed string(using loops) is : ",end="")   
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

def reverse(s):   
  _str = ""   
  for i in s:   
    _str = i + _str 
  return _str 
    
string = "C# Corner"  
    
print ("The original string  is : ",end="")   
print (string)   
    
print ("The reversed string(using loops) is : ",end="")   
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

def reverse(s):   
    if len(s) == 0:   
        return s   
    else:   
        return reverse(s[1:]) + s[0]   
    
_str = "C# Corner"  
    
print ("The original string  is : ",end="")   
print (_str)   
    
print ("The reversed string(using recursion) is : ",end="")  
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"

def reverse(string):   
    string = "".join(reversed(string))   
    return string   
    
_str = "C# Corner"  
    
print ("The original string  is : ",end="")   
print (_str)   
    
print ("The reversed string(using reversed) is : ",end="")  
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.

str = "C# Corner"  
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:

str = "C# Corner"  
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.

_str = "C# Corner"  
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.​​​​​​​

_str = "C# Corner"  
N_of_char = 2  
for i in range(0,N_of_char):  
    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.


Similar Articles