How to Get the Last N characters of a String in Python


String Manipulation is an important task in Python. This may involve slicing the string, taking N characters, etc. These are essential tasks in Text preprocessing, like in NLP tasks, Password and data security, string comprehension and encoding, etc. Fortunately, Python offers a variety of ways to perform string manipulation. In this article, we will learn how to obtain the last N characters in a String in Python.

Using for Loop

The loop is a very common expression for most programming languages. This allows us to iterate over iterable objects, generate a series of values, and more. Since the String objects are iterable, we can utilize the for loop to get the last n characters of the String. Since the indexing of iterable objects starts from 0, ends, and extends to length−1, the index of the last n characters of the String is from length−n−1 to length−1.

Example

In the following example, we created a function named get_last_n_characters that takes the String and n as the parameter. It is a non−void function and returns the last n characters of the String. Under the function, we have declared an empty String named last_n_characters and iterated over the last n characters of the String using the range expression. We appended the characters of the String into the empty String and returned the final String.

def get_last_n_characters(text, n):
    last_n_characters=""
    for i in range(len(text) - 1, len(text) - n - 1, -1):
        last_n_characters = text[i] + last_n_characters
    return last_n_characters
text = "Hello, world!"
n = 5
result = get_last_n_characters(text, n)
print(f"The last {n} characters of the String are: {result}")

Output

The last 5 characters of the String are: orld!

Use While Loop

The while loop is another popular expression in Python, like the for loop. However, the only difference is that we use the while loop when we need clarification on how many times we need to run the loop. When we meet a specific condition, we complete the loop.

Example

In the following code we have created the function get_last_n_characters. Under this function, we have initialized an empty String. We iterated through the last n characters of the String through the while loop, and under each iteration, we have appended the character into the initialized String.

def get_last_n_characters(text, n):
    last_n_characters = ""
    index = len(text) - 1
    while n > 0 and index >= 0:
        last_n_characters = text[index] + last_n_characters
        index -= 1
        n -= 1
    return last_n_characters

text = "Hello, world!"
n = 9
result = get_last_n_characters(text, n)
print(f"The last {n} characters of the string are: {result}")

Output

The last 9 characters of the string are: o, world!

Using The String Slicing

Slicing the string is an important concept in most of the programming languages. In Python, slicing uses the concept of indexing property.

Syntax

string[a:b]

Here string is the name of the String object. a here refers to the index with which we need to start slicing, and b is the index to which we need to slice. Note that a is inclusive, but b is exclusive. If we do not specify, Pyon will take the default value as 0. On the other hand, if we do not specify b, then Python will take the default value of b as n.

Example

In the following code, we used the built−in method of String to access the last n characters. We used the String slicing where we passed −n as the starting index and default as the end index. Hence as indexing property, the method slices the string and returns the last n characters of the String.

def get_last_n_characters(string, n):
    last_n_characters = string[-n:]
    return last_n_characters
text = "Hello, world!"
n = 5
result = get_last_n_characters(text, n)
print(f"The last {n} characters of the String are: {result}")

Output

The last 5 characters of the String are orld!

Use Slice Method

The slice method allows you to create a slice object that you can use to extract a portion of the sequence. We can pass this slice object to the String, returning the required characters.

Syntax

slice(-start, end)

Here the slice is a keyword and an in−built method in Python. −start indicates that we want to start slicing the string from the character having index =-start. end refers to the index up to which we need to perform the slicing. Since we specified None, we will have the slicing up to the last character of the String.

Example

In the following code, we used the slice method of Python to get the last n characters of the String. We have defined the first argument, aka the starting index, to be −n, indicating that we want to start the slicing from the n last characters of the String. We set the end index's value to be None, indicating that we want to slice up to the last characters.

def get_last_n_characters(string, n):
    last_n_characters = slice(-n, None)
    return string[last_n_characters]

text = "Hello, world!"
n = 5
result = get_last_n_characters(text, n)
print(f"Last {n} characters of the String is: {result}")

Output

Last 5 characters of the String is: orld!

Using The Join and Reversed Method

In Python, the join() and reversed() methods are commonly used for manipulating strings and sequences.

The join() method is a string method that concatenates the elements of an iterable, such as a list or tuple, into a single string. It takes the iterable as its parameter and returns a new string that joins the elements with a specified separator.

Syntax

new_string = separator.join(iterable)

Here new_string is the resulting string after joining the elements. The separator is a string used as a separator between the elements. The iterable is an iterable containing the elements to be joined.

The reversed() method is a built−in function in Python that returns an iterator that yields the elements of a sequence in reverse order. It can be used with strings, lists, tuples, or any other sequence type.

Syntax

reversed_sequence = reversed(sequence)

Here the reversed_sequence is an iterator object containing the sequence elements in reverse order. The sequence is the sequence from which the reversed elements are obtained.

Example

We combined joined, reversed, and indexing properties in the following code to get the last n characters. The reverse method reverses the String, and the slicing method extracts the first n characters. Again using the indexing method "[::-1]" we have reversed the String. This restores the original order of the characters.

def get_last_n_characters(string, n):
    last_n_characters = ''.join(reversed(string))[:n][::-1]
    return last_n_characters
text = "Hello, world. I am testing this message"
n = 6
result = get_last_n_characters(text, n)
print(f"Last {n} characters of the String is: {result}")

Output

Last 6 characters of the String is: essage

Using deque And join Method

In Python, the join() method and the deque class from the collections module are commonly used for string manipulation and managing iterable objects efficiently.

The deque class is part of the collections module in Python and provides a double−ended queue. It allows efficient operations for adding and removing elements from both ends of the queue. It can be initialized with an iterable or without any arguments.

Syntax

collections.deque(iterable, maxlen)

Here the deq is the deque object that holds the elements. The iterable is optional and iterable whose elements are added to the deque. If not specified, an empty deque is created.maxlen is another optional parameter that specifies the maximum length of the deque. Adding elements beyond this limit will remove elements from the opposite end if specified.

By combining the join() method and the deque class with a specified maxlen, such as join(deque(string, maxlen=n)), you can efficiently extract a portion of a string or sequence while limiting the length of the resulting joined string.

Example

In the following example, we first imported the deque method from the collections library of Python. Next, we used the deque method to access the last n characters of the String. We passed the string and maxlen=n as the parameter to the String. We used the join method to concatenate to the empty String.

from collections import deque
def get_last_n_characters(string, n):
    last_n_characters = ''.join(deque(string, maxlen=n))
    return last_n_characters
text = "Hello, world. I am testing this message"
n = 11
result = get_last_n_characters(text, n)
print(f"Last {n} characters of the String is: {result}")

Output

Last 11 characters of the String is: his message

Conclusion

In this article, we have learned how to get the last N characters of a String using different in−built methods and programming techniques. First, we learned how to use the slicing operation to get the last N characters of a String in Python. Next, we have seen the usage of the slice method, string method, and some in−built functions like deque to get the last N characters of a String. We highly recommend the readers try the examples to understand the topics better.

Updated on: 18-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements