Remove the last N characters from a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Remove the last N characters from a String in Python
  2. Remove the last N characters if they are equal to a certain value
  3. Remove the last N characters from a String using positive slicing
  4. Remove the last N characters from a String using a for loop

# Remove the last N characters from a String in Python

Use negative string slicing to remove the last N characters from a string, e.g. new_string = string[:-N].

The slice will remove the last N characters from the string by returning a copy of the string that goes up to, but not including the last N characters.

main.py
string = 'bobbyhadz.com' # โœ… Remove the last 2 characters from string new_string = string[:-2] print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz.c # โœ… Remove the last 3 characters from a string new_string = string[:-3] print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz. # โœ… Remove the last 4 characters from a string new_string = string[:-4] print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz

remove last n characters from string

The code for this article is available on GitHub

We used string slicing to remove the last N characters from a string.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

Negative indices can be used to count backward, e.g. my_string[-1] returns the last character in the string and my_string[-2] returns the second to last item.

The slice string[:-2] starts at index 0 and goes up to, but not including the second to last character in the string.

main.py
string = 'bobbyhadz.com' new_string = string[:-2] print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz.c

In other words, the slice returns a new string that doesn't contain the last 2 characters of the original string.

If you don't need to keep the original variable around, reassign it rather than declaring a new variable.

main.py
string = 'bobbyhadz.com' string = string[:-3] print(string) # ๐Ÿ‘‰๏ธ bobbyhadz.

The slice string[:-3] starts and index 0 and goes up to, but not including the last 3 characters in the string.

# Remove the last N characters if they are equal to a certain value

If you only want to remove the last N characters from a string if they are equal to a certain value, use the str.endswith() method.

main.py
string = 'bobbyhadz.com' substring = 'com' if string.endswith(substring): string = string[:-len(substring)] print(string) # ๐Ÿ‘‰๏ธ bobbyhadz.

remove last n characters if they are equal to certain value

The code for this article is available on GitHub

The example only removes the last 3 characters from the string if the string ends with the specified characters.

The str.endswith() method returns True if the string ends with the provided suffix, otherwise the method returns False.

Alternatively, you can use positive string slicing.

# Remove the last N characters from a String using positive slicing

This is a three-step process:

  1. Get the string's length and subtract N.
  2. Get a slice of the string starting at index 0 and going up to the string's length minus N.
  3. The new string won't contain the last N characters.
main.py
string = 'bobbyhadz.com' new_string = string[:len(string)-2] print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz.c new_string = string[:len(string)-3] print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz. new_string = string[:len(string)-4] print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz

remove last n characters from string using positive slicing

The code for this article is available on GitHub

We used the len() function to get the length of the string.

The len() function returns the length (the number of items) of an object.

main.py
print(len('ab')) # ๐Ÿ‘‰๏ธ 2 print(len('abc')) # ๐Ÿ‘‰๏ธ 3

A string's length is always going to be last_index + 1 because indices are zero-based in Python.

For example, if a string has a length of 10, the last index in the string is 9.

If you specify a stop index of 9 (or len(string) - 1), you would remove the last character from the string because stop indices are exclusive (up to but not including).

Similarly, if you specify a stop index of 8 (or len(string) - 2), you would remove the last 2 characters from the string.

Alternatively, you can use a for loop.

# Remove the last N characters from a String using a for loop

This is a three-step process:

  1. Use a for loop to iterate over the string with enumerate().
  2. Check if the current index is less than the length of the string - N.
  3. If the condition is met, append the character to a new string.
main.py
string = 'bobbyhadz.com' new_string = '' n = 3 for index, char in enumerate(string): if index < len(string) - n: new_string += char print(new_string) # ๐Ÿ‘‰๏ธ bobbyhadz.
The code for this article is available on GitHub

We used the enumerate() function to get access to the index of the current iteration.

main.py
string = 'abc' for index, char in enumerate(string): print(char, index) # ๐Ÿ‘‰๏ธ a 0, b 1, c 2

The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

On each iteration, we check if the current index is less than the string's length minus N.

This is very similar to the positive slicing approach from the previous example.

If the condition is met, we add the current character to a new string.

The += operator is a shorthand for new_string = new_string + char.

Which approach you pick is a matter of personal preference. I'd use the negative string slicing approach as I find it quite direct and readable.

I've also written an article on how to remove the first N characters from a string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev