The slicing syntax lets you remove a particular character or range of characters from a string based on the index values of those characters.
This guide discusses how to remove the first
n characters from a string in Python. It walks through an example of the slicing syntax so that you can learn how to use it in your own programs.
Python: String Indexing
Index numbers begin with zero and increase incrementally by one for each character. Let’s take a look at a string:
The string contains four characters. The first character, “P”, has the index number 0. The last character,
!, has the index number 4.
You can use these numbers to retrieve individual characters or remove characters from a string.
Remove the First n Characters from a String in Python
Here, write a program that removes the first four characters from the receipts that are stored by a donut store. These characters represent the ID of a purchase but are no longer relevant due to a systems upgrade.
To start, define a list of receipts and a new list where you can store the new receipts:
receipts = [ "107 Strawberry donut $2.00", "297 Blueberry donut $2.10", "342 Raspberry donut $2.10" ] new_receipts = 
The three numbers at the start of the list is the purchase ID. There is also a space that follows the ID that you want to remove.
Use a “for” loop to iterate over each receipt in the list so you can remove the first four characters from each receipt:
for r in receipts: new_r = r[4:] new_receipts.append(new_r)
This code removes the first four characters from each receipt in the “receipts” list. A new string without these characters is assigned to the variable “new_r” with the matched characters removed. You do this because strings are immutable and you cannot modify an existing string.
Next, add the new receipt to the “new_receipts” list. Finally, print the “new_receipts” list to the console so you can see if the code has worked:
Run the code and see what happens:
['Strawberry donut $2.00', 'Blueberry donut $2.10', 'Raspberry donut $2.10']
The code has successfully removed the first four characters from each of the original strings.
If you wanted to remove more or fewer characters, you would replace the number 4 with the number of characters you wanted to remove. To remove only the first two characters from the strings, you would use this code:
new_r = r[2:]
With this line of code, the program would return:
['7 Strawberry donut $2.00', '7 Blueberry donut $2.10', '2 Raspberry donut $2.10']
You can remove the first
n characters from a string using slicing syntax. This syntax lets you retrieve a particular part of a string based on a particular index value.
Now you have the knowledge you need to use slicing to remove characters from the start of a Python string like a professional coder!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.