Open In App

Get Last N characters of a string – Python

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = “geeks” and n = 2, then the output will be “ks”. Let’s explore the most efficient methods to achieve this in Python.

Using String Slicing

String slicing is the fastest and most straightforward way to get the last N characters from a string. It’s built into Python and highly optimized for such tasks.

Python
s = "Geeks for Geeks"
n = 5

ch = s[-n:]
print(ch)

Output
Geeks

Explanation:

  • slicing operation s[-n:] retrieves the substring starting from the Nth position from the end to the end of the string.
  • this approach is computationally efficient and widely used in text processing tasks.

Using a For Loop

If we want more manual control, a for loop can extract the last N characters. Even though it’s less efficient, it’s clear and easy to understand.

Python
s = "Geeks for Geeks"
n = 5

ch = ""
for i in range(len(s) - n, len(s)):
    ch += s[i]

print(ch)

Output
Geeks

Explanation:

  • loop iterates over the string, starting from the Nth position from the end and appending each character to the result.
  • it’s slower and less memory-efficient than slicing.

Using a Deque from the Collections Module

For large strings or streaming data, the deque from the collections module provides a memory-efficient way to manage the last N characters.

Python
from collections import deque

s = "Geeks for Geeks"
n = 5

ch = deque(maxlen=n)
for c in s:
    ch.append(c)

print("".join(ch))

Output
Geeks

Explanation:

  • The deque is initialized with a fixed size (maxlen). It automatically retains only the last N elements as new characters are appended.
  • This method is ideal for scenarios involving continuous data streams but might be excessive for smaller strings.

Using endswith Method

While not directly extracting the characters, the endswith method is helpful if you want to confirm whether a string ends with specific characters.

Python
s = "Geeks for Geeks"
suf= "Geeks"

if s.endswith(suf):
    print(suf)

Output
Geeks

Explanation:

  • endswith method checks if the string terminates with the specified characters.
  • it’s useful for validation tasks and complements other string operations.


Next Article

Similar Reads