Python Program to remove the last specified character from the string

Removing the last specified character from a string is a common text manipulation task in Python. This operation is useful for data cleaning, input validation, and string formatting. Python provides several approaches including slicing, rstrip(), and string replacement methods.

Method 1: Using String Slicing

String slicing with [:-1] removes the last character by excluding it from the slice ?

text = "Tutorialspoints"
result = text[:-1]
print("Original string:", text)
print("After removing last character:", result)
Original string: Tutorialspoints
After removing last character: Tutorialspoint

Method 2: Using rstrip() for Specific Character

The rstrip() method removes specified characters from the right end of the string ?

text = "ROCK AND ROLLS"
result = text.rstrip('S')
print("Original string:", text)
print("After removing 'S':", result)
Original string: ROCK AND ROLLS
After removing 'S': ROCK AND ROLL

Method 3: Using Loop and String Concatenation

Building a new string by iterating through all characters except the last one ?

text = "INTERPRETERS"
result = ""
for i in range(len(text) - 1):
    result += text[i]
print("Original string:", text)
print("After removing last character:", result)
Original string: INTERPRETERS
After removing last character: INTERPRETER

Method 4: Using replace() with endswith()

This method checks if the string ends with a specific character before removing it ?

text = "abcdefghi"
char_to_remove = "i"

if text.endswith(char_to_remove):
    result = text.replace(char_to_remove, "", 1)
else:
    result = text

print("Original string:", text)
print("After removing last '" + char_to_remove + "':", result)
Original string: abcdefghi
After removing last 'i': abcdefgh

Comparison

Method Best For Removes Specific Char? Performance
Slicing [:-1] Always remove last char No Fastest
rstrip() Remove specific trailing chars Yes Fast
Loop + concatenation Learning purposes No Slowest
replace() + endswith() Conditional removal Yes Moderate

Conclusion

Use slicing [:-1] for simple last character removal. Use rstrip() when you need to remove specific trailing characters. The replace() method with endswith() provides conditional removal based on the last character.

Updated on: 2026-03-27T07:09:37+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements