Skip to main content

How to Remove the Last N Characters from a String in Python

This guide explains how to efficiently remove the last N characters from a string in Python. We'll primarily focus on using negative string slicing, the most concise and Pythonic approach. We'll also cover conditional removal of trailing characters.

Negative slicing is the most direct and efficient way to remove characters from the end of a string. The syntax is string[:-N].

string = 'tutorialreference.com'

new_string = string[:-2] # Remove last 2 characters
print(new_string) # Output: tutorialreference.c

new_string = string[:-3] # Remove last 3 characters
print(new_string) # Output: tutorialreference.

new_string = string[:-4] # Remove the last 4 characters
print(new_string) # Output: tutorialreference
  • string[:-N]: This creates a new string that contains all characters from the beginning of string up to (but not including) the character at index -N. Negative indices count from the end of the string. So, -1 is the last character, -2 is the second-to-last, and so on.
  • You can reassign the original variable instead of creating a new one, if you don't need it anymore.

Edge Cases:

  • Empty string: If the string is empty, slicing with any N will return an empty string.

  • N is greater than or equal to string length: If N is greater than or equal to the string's length, slicing returns an empty string.

    string = 'tutorialreference.com'
    print(string[:-100]) # Output "" (empty string)
    empty_string = ""
    print(empty_string[:-2]) # Output: "" (empty string)
  • Negative slicing handles these edge cases, without a need to add extra checks.

Conditional Removal of Trailing Characters

If you only want to remove the last N characters if they match a specific substring, use endswith():

string = 'tutorialreference.com'
substring = 'com'

if string.endswith(substring):
string = string[:-len(substring)]

print(string) # Output: tutorialreference.
  • The endswith() method is used to check the ending part of the string.
  • If the string ends with substring, this code removes the matching suffix.
  • If the string does not end with the substring, the original string will be unchanged.