Skip to Content

Python – Remove First N Characters From String

In this tutorial, we will look at how to remove the first n characters from a string in Python with the help of some examples.

remove first n characters from string

Python strings are immutable which means that they cannot be modified. However, you can create a copy of the string with the first n characters removed and assign it to the original string variable.

To remove the first n characters from a string, slice the string from the nth index to the end of the string. Note that characters in a string are indexed starting from zero, so slicing the string from the nth index to the end would remove the first n characters of the string. The following is the syntax –

# remove first n characters from a string
s = s[n:]

It returns a copy of the original string with the first n characters removed.

Let’s look at some examples -.

In this case n = 2, hence we slice the string from index 2 to the end of the string.

# create a string
s = "Hufflepuff"
# remove first 2 characcters
print(s[2:])

Output:

fflepuff

You can see that the resulting string does not have the first two characters from the original string.

We can similarly use the above syntax to remove the first three characters from a string.

# create a string
s = "Hufflepuff"
# remove first 3 characcters
print(s[3:])

Output:

flepuff

The resulting string has the first three characters removed.

You might also be interested in –

Author

  • Piyush

    Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.