Python program to remove last N characters from a string
Last Updated :
23 Jul, 2025
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 Slicing
String slicing is one of the simplest and most efficient ways to manipulate strings in Python. By leveraging slicing, we can easily remove the last N characters from a string with minimal code.
Python
s = "GeeksForGeeks"
n = 3
# Remove the last N characters
result = s[:-n]
print(result)
Explanation:
s[:-n]
slices the string from the start to the position len(s) - n
, effectively removing the last N
characters.- If
n
is 0, it keeps the entire string unchanged.
Let's explore various other methods :
Using a Loop
Using a loop, we can iteratively construct a new string by excluding the last N characters from the original string
Python
s = "GeeksForGeeks"
n = 3
# Remove the last N characters
result = ""
for i in range(len(s) - n):
result += s[i]
print(result)
Explanation:
- This approach iterates through the string up to
len(s) - n
and appends each character to a new string, omitting the last N
characters.
Using rstrip
with Conditions
The rstrip
method, combined with conditions, allows us to remove the last N characters by treating them as a specific substring to strip.
Python
# Input string and N
s = "GeeksForGeeks"
n = 3
# Remove the last N characters
result = s.rstrip(s[-n:]) if n > 0 else s
print(result)
Explanation:
rstrip(s[-n:])
removes the last N
characters by treating them as a substring to strip.- This approach is useful if the string has trailing characters that match those being removed.
Using join
and List Slicing
By combining list slicing with join
, we can efficiently create a new string that excludes the last N characters from the original.
Python
s = "GeeksForGeeks"
n = 3
# Remove the last N characters
result = ''.join(s[:len(s) - n])
print(result)
Explanation:
- This approach slices the string up to
len(s) - n
and then joins the resulting characters into a new string.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice