Remove first n characters from a string in Python
In this tutorial, we will learn how to remove the first n characters from a string in Python.
We will cover these:
- The simplest way to remove the first n characters. (Slice notation)
- Using regular expressions to do the same.
- Using replace.
If you follow my tutorials, then you may notice that in each of my tutorials, I always start with the easiest method first. This tutorial is not a different one.
Slice notation in Python to remove the first n characters from a string
Syntax:
string[n:]
There are starting and ending index parameters in this slice notation. But I am not going deeper as this tutorial is only about removing the first few characters.
myString = "CodeSpeedy makes your day easier" finalString = myString[1:] print(finalString)
Output:
odeSpeedy makes your day easier
We have used [1:]
as we wanted to remove the first 1 character from the string.
Now, if we want to remove the first 4 characters:
myString = "CodeSpeedy makes your day easier" finalString = myString[4:] print(finalString)
Output:
Speedy makes your day easier
Note that: We are reassigning the string instead of directly changing it because the string is immutable in Python.
Regular expression to remove first n characters from a string in Python
The syntax will be:
re.sub(r'.', '', myString, count = n)
n is the number that denotes how many characters will be removed.
Here we are simply replacing the first n number of characters to ''
which is actually nothing. In this way we are removing the n number of characters from any string.
Let’s dive into the same using regex:
import re myString = "CodeSpeedy makes your day easier" finalString = re.sub(r'.', '', myString, count = 1) print(finalString)
Output:
odeSpeedy makes your day easier
Note that: I am using r
at the beginning of re.sub()
. This r
tells our program to consider this string as raw string.
It is a good practice to use raw string in case of using regex in Python. It will be useful if backslashes are found in our string.
Replace method to remove first specific number of characters from a string in Python
myString = "CodeSpeedy makes your day easier" finalString = myString.replace(myString[:4], '') print(finalString)
Output:
Speedy makes your day easier
Here, we are just replacing the first 4 characters of the string with nothing.
Now you can choose your best option from the above methods. If you find any other options you can write that in the comment section.
Leave a Reply