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 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.
s = "GeeksForGeeks"
n = 3
# Remove the last N characters
result = s[:-n]
print(result)
Output
GeeksForGe
Explanation:
s[:-n]
slices the string from the start to the positionlen(s) - n
, effectively removing the lastN
characters.- If
n
is 0, it keeps the entire string unchanged.
Let’s explore various other methods :
Table of Content
Using a Loop
Using a loop, we can iteratively construct a new string by excluding the last N characters from the original string
s = "GeeksForGeeks"
n = 3
# Remove the last N characters
result = ""
for i in range(len(s) - n):
result += s[i]
print(result)
Output
GeeksForGe
Explanation:
- This approach iterates through the string up to
len(s) - n
and appends each character to a new string, omitting the lastN
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.
# 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)
Output
GeeksForG
Explanation:
rstrip(s[-n:])
removes the lastN
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.
s = "GeeksForGeeks"
n = 3
# Remove the last N characters
result = ''.join(s[:len(s) - n])
print(result)
Output
GeeksForGe
Explanation:
- This approach slices the string up to
len(s) - n
and then joins the resulting characters into a new string.