Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Split String into List of characters in Python
Next article icon

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
Split String into List of characters in Python

S

sidgautam
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Python Programs
  • Technical Scripter 2020
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach. Using for loopThe simplest way to iterate over the characters in
    2 min read
  • Python | Lowercase first character of String
    The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the first character of the string to lowercase. Let us discuss certain ways in which this can be performed. Method #1: Using string sli
    4 min read
  • Split String into List of characters in Python
    We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
    2 min read
  • Python - Least Frequent Character in String
    The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count. Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it ea
    3 min read
  • Count the number of characters in a String - Python
    The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Let’s explore different approaches to accomplish this. Using len()len() i
    3 min read
  • Python | Longest Run of given Character in String
    Sometimes, while working with Strings, we can have a problem in which we need to perform the extraction of length of longest consecution of certain letter. This can have application in web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method
    6 min read
  • Python | Get positional characters from String
    Sometimes, while working with Python strings, we can have a problem in which we need to create a substring by joining the particular index elements from a string. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute method in which this task can be pe
    5 min read
  • Python program to remove last N characters from a string
    In this article, we’ll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
    2 min read
  • Python - Extract range characters from String
    Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk
    4 min read
  • Python - Extract only characters from given string
    To extract only characters (letters) from a given string we can use various easy and efficient methods in Python. Using str.isalpha() in a Loop str.isalpha() method checks if a character in a string is an alphabetic letter. Using a loop, we can iterate through each character in a string to filter ou
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences