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.
Below is the definition of string slicing:
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:
lstrip is mainly used to remove blank spaces from the start of a string in python. This method is defined as below:
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
- Python program to count the total number of lines in a file
- Python program to find larger string among two strings
- Python program to find the first odd Abundant or excessive number
- Python program to count the frequency of each words in a string
- Python program to check if a number is abundant/excessive or not
- Python program to capitalize first letter of each words of a string