Remove Last N Characters from String in Python

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Given a string, the task is to remove last n characters from string.

Examples:

Input:

string="BTechGeeks" n=3

Output:

BTechGe

Remove Last N Characters from String

There are several ways to remove last n characters from string some of them are:

Method #1:Using slicing

It returns the characters of the string as a new string from index position start to end -1. The default values for start and end are 0 and Z, where Z is the length of the string. If neither start nor end are specified, it selects all characters in the string, from 0 to size-1, and creates a new string from those characters.

This slicing technique can be used to cut out a piece of string that includes all characters except the last N characters.

Below is the implementation:

# function which removes last n characters of string
def removeLastN(string, n):
    # calculate the size of string
    size = len(string)
    # removing last n characters of string
    string = string[:size-n]
    # return the string
    return string


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removeLastN function
print(removeLastN(string, n))

Output:

BTechGe

Method #2 : Using for loop

To delete the last N characters from a string, we can iterate through the string’s characters one by one, selecting all characters from index position 0 until the size – n of the string.

Below is the implementation:

# function which removes last n characters of string
def removeLastN(string, n):
    # taking a empty string
    newstr = ""
    # removing last n characters of string using for loop
    # Traverse the string from 0 to sizr-n
    for i in range(0, len(string)-n):
        newstr = newstr+string[i]

    # return the string
    return newstr


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removelastN function
print(removeLastN(string, n))

Output:

BTechGe

Method #3 :Using regex to remove last two characters

In Python, we can use regex to match two groups in a string, i.e.

Group 1: The first N characters in a string
Group 2 consists of every character in the string except the first N characters.
The string is then modified by replacing both groups with a single group, group 1.

Below is the implementation:

import re

def removeGroup(k):
    # Only group 1 should be returned from the match object.
        # Other groups should be deleted.
    return k.group(1)

# given string
string = "BTechGeeks"
result = re.sub("(.*)(.{2}$)", removeGroup, string)
print(result)

Output:

BTechGee

 
Related Programs: