Remove last N characters from string in Python

In this article we will discuss different ways to delete last N characters from a string i.e. using slicing or for loop or regex.

Remove last N character from string by slicing

In python, we can use slicing to select a specific range of characters in a string i.e.

str[start:end]

It returns the characters of the string from index position start to end -1, as a new string. Default values of start & end are 0 & Z respectively. Where Z is the size of the string.

It means if neither start nor end are provided, then it selects all characters in the string i.e. from 0 to size-1 and creates a new string from those characters.

We can use this slicing technique to slice out a piece of string, that includes all characters of string except the last N characters. Let’s see how to do that,

Remove last 3 character from string using Slicing & Positive Indexing

Suppose our string contains N characters. We will slice the string to select characters from index position 0 to N-3 and then assign it back to the variable i.e.

org_string = "Sample String"

size = len(org_string)
# Slice string to remove last 3 characters from string
mod_string = org_string[:size - 3]

print(mod_string)

Output

Sample Str

By selecting characters in string from index position 0 to N-3, we selected all characters from string except the last 3 characters and then assigned this sliced string back to the same variable again, to give an effect that final 3 characters from string are deleted.

P.S. We didn’t explicitly provided 0 as start index, because its default value is 0. So we just skipped it.

Remove last character from string using Slicing & Positive Indexing

org_string = "Sample String"

size = len(org_string)

# Slice string to remove last character from string
mod_string = org_string[:size - 1]

print(mod_string)

Output

Sample Strin

By selecting characters in string from index position 0 to size-1, we selected all characters from string except the last character.

The main drawback of positive indexing in slicing is: First we calculated the size of string i.e. N and then sliced the string from 0 to N-1. What if we don’t want to calculate the size of string but still want to delete the characters from end in a string?

Remove last N characters from string Using negative slicing

In python, we can select characters in a string using negative indexing too. Last character in string has index -1 and it will keep on decreasing till we reach the start of the string.

For example for string “Sample”,

Index of character ‘e’ is -1
Index of character ‘l’ is -2
Index of character ‘p’ is -3
Index of character ‘m’ is -4
Index of character ‘a’ is -5
Index of character ‘S’ is -6

So to remove last 3 characters from a string select character from 0 i.e. to -3 i.e.

org_string = "Sample String"

# Slice string to remove 3 last characters
mod_string = org_string[:-3]

print(mod_string)

Output

Sample Str

It returned the a new string built with characters from start of the given string till index -4 i.e. all except last 3 characters of the string. we assigned it back to the string to gave an effect that last 3 characters of the string are deleted.

Remove last characters from string Using negative slicing

To remove last character from string, slice the string to select characters from start till index position -1 i.e.

org_string = "Sample String"

# Slice string to remove 1 last character
mod_string = org_string[:-1]

print(mod_string)

Output

Sample Strin

It selected all characters in the string except the last one.

Remove final N characters from string using for loop

We can iterate over the characters of string one by one and select all characters from start till (N -1)th character in the string. For example, let’s delete last 3 characters from a string i.e.

org_string = "Sample String"

n = 3

mod_string = ""
# Iterate over the characters in string and select all except last 3
for i in range(len(org_string) - n):
    mod_string = mod_string + org_string[i]

print(mod_string)

Output

Sample Str

To remove last 1 character, just set n to 1.

Remove Last N character from string using regex

We can use regex in python, to match 2 groups in a string i.e.

  • Group 1: Every character in string except the last N characters
  • Group 2: Last N character of string

Then modify the string by substituting both the groups by a single group i.e. group 1.

For example, let’s delete last 3 characters from string using regex,

import re

def remove_second_group(m):
    """ Return only group 1 from the match object
        Delete other groups """
    return m.group(1)

org_string = "Sample String"

# Remove final 3 characters from string
result = re.sub("(.*)(.{3}$)", remove_second_group, org_string)

print(result)

Output

Sample Str

Here sub() function matched the given pattern in the string and passed the matched object to our call-back function remove_second_group(). Match object internally contains two groups and the function remove_second_group() returned a string by selecting characters from group 1 only. Then sub() function replaced the matched characters in string by the characters returned by the remove_second_group() function.

To remove last character from string using regex, use {1} instead,

org_string = "Sample String"

# Remove final n characters from string
result = re.sub("(.*)(.{1}$)", remove_second_group, org_string)

print(result)

Output

Sample Strin

It removed the last character from the string

Remove last character from string if comma

It might be possible that in some scenarios we want to delete the last character of string, only if it meets a certain criteria. Let’s see how to do that,

Delete last character from string if it is comma i.e.

org_string = "Sample String,"

if org_string[-1] == ',':
    result = org_string[:-n-1]

print(result)

Output:

Sample String

So, this is how we can delete last N characters from a string in python using regex and other techniques.

The complete example is as follows,

import re


def remove_second_group(m):
    """ Return only group 1 from the match object
        Delete other groups """
    return m.group(1)


def main():

    print('***** Remove last character N from string by slicing *****')

    print('*** Remove Last 3 characters from string by slicing using positive indexing***')

    org_string = "Sample String"

    size = len(org_string)
    # Slice string to remove last 3 characters from string
    mod_string = org_string[:size - 3]

    print(mod_string)

    print('*** Remove Last character from string by slicing using positive indexing***')

    org_string = "Sample String"

    size = len(org_string)

    # Slice string to remove last character from string
    mod_string = org_string[:size - 1]

    print(mod_string)


    print('***** Using negative slicing to remove last N characters from string *****')

    print('*** Remove Last 3 characters from string by slicing using negative indexing***')

    org_string = "Sample String"

    # Slice string to remove 3 last characters
    mod_string = org_string[:-3]

    print(mod_string)

    print('*** Remove Last character from string by slicing using negative indexing***')

    org_string = "Sample String"

    # Slice string to remove 1 last character
    mod_string = org_string[:-1]

    print(mod_string)


    print('***** Remove Last N characters from string using for loop *****')

    org_string = "Sample String"

    n = 3

    mod_string = ""
    # Iterate over the characters in string and select all except last 3
    for i in range(len(org_string) - n):
        mod_string = mod_string + org_string[i]

    print(mod_string)

    print('***** Remove Last N character from string using regex *****')

    print('*** Remove Last 3 characters from string using regex ***')

    org_string = "Sample String"

    # Remove final 3 characters from string
    result = re.sub("(.*)(.{3}$)", remove_second_group, org_string)

    print(result)

    print('*** Remove last character from string using regex ***')

    org_string = "Sample String"

    # Remove final n characters from string
    result = re.sub("(.*)(.{1}$)", remove_second_group, org_string)

    print(result)

    print('***** Remove last character from string if comma *****')

    org_string = "Sample String,"

    if org_string[-1] == ',':
        result = org_string[:-1]

    print(result)


if __name__ == '__main__':
    main()

Output:

***** Remove last character N from string by slicing *****
*** Remove Last 3 characters from string by slicing using positive indexing***
Sample Str
*** Remove Last character from string by slicing using positive indexing***
Sample Strin
***** Using negative slicing to remove last N characters from string *****
*** Remove Last 3 characters from string by slicing using negative indexing***
Sample Str
*** Remove Last character from string by slicing using negative indexing***
Sample Strin
***** Remove Last N characters from string using for loop *****
Sample Str
***** Remove Last N character from string using regex *****
*** Remove Last 3 characters from string using regex ***
Sample Str
*** Remove last character from string using regex ***
Sample Strin
***** Remove last character from string if comma *****
Sample String

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top