Python program to remove the first n characters from a string

Python prgram to remove the first n characters from a string:

In this post, we will learn how to remove the first n characters from a string in Python. String is immutable or we can’t modify a string. Only thing we can do is that we can create one different string from the current string with some modification.

For example, if the string is hello and we are removing the first 3 characters from that string, it will be lo.

We can use string slicing or lstrip methods to remove starting characters from a string. string slicing is easy and it is the recommended one.

Example to remove first n characters from a string using slice in python:

Below is the definition of string slicing:

str[start:stop]

It will return one substring from start to stop. If we don’t provide start, it will start from the start of the string. Similarly, if we don’t provide stop, it will stop at the end of the string.

For our use case, if we want to remove the first n characters from a string, we can use str[len-n:] for that, where len is the length of the string. For example, if the string is universe and if we want to remove the first two characters, we can use str[8-2:]. Where, 8 is the size of universe and 2 is the number of characters we are removing.

Let’s take a look at the example:

given_string = 'universe'
start = len(given_string) - 4

print(given_string[start:])

It will print:

erse

Using lstrip:

lstrip is mainly used to remove blank spaces from the start of a string in python. This method is defined as below:

str.lstrip([chrs])

Here, chrs are characters that we want to remove from the start of a string. But this is an optional value. If we don’t provide it, it removes the blank spaces.

The return value of this method is the new string.

So, in our case, we will use this method to remove the first n characters from a string by using with string slicing. String slicing will return us the first n characters that we want to remove from the string and if we pass it to lstrip, it will return us the required string.

Below is the program:

given_str = 'universe'

print(given_str.lstrip(given_str[:1]))
print(given_str.lstrip(given_str[:2]))
print(given_str.lstrip(given_str[:3]))

Here, the first statement removes the first 1 character from the string given_str, the second one removes 2 characters and the third one removes first 3 characters. It will print the below output:

niverse
iverse
verse

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊