Remove First 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 first n characters from string.

Examples:

Input:

string="BTechGeeks" n=3

Output:

chGeeks

Remove First N Characters from String

There are several ways to remove first 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 first N characters.

Below is the implementation:

# function which removes first n characters of string
def removeFirstN(string, n):
    # removing first n characters of string
    string = string[n:]
    # return the string
    return string


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

Output:

chGeeks

Method #2 : Using for loop

To delete the first N characters from a string, we can iterate through the string’s characters one by one, selecting all characters from index position N until the end of the string.

Below is the implementation:

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

    # return the string
    return newstr


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

Output:

chGeeks

Method #3 :Using regex to remove first 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 2.

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(2)
# given string
string = "BTechGeeks"
result = re.sub("(^.{2})(.*)", removeGroup, string)
print(result)

Output:

echGeeks

Related Programs: