Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to delete prefix substring from the given string
In this article, we will learn how to create a Python program to delete prefix substrings from a given string. A prefix is a group of characters that are added to the beginning of a string. When working with text data, you often need to remove common prefixes to clean or process the data efficiently.
For example, if the given string is "My shirt color is Red" and we want to delete the prefix "My", the final output becomes " shirt color is Red".
Methods for Removing Prefixes
Method 1: Using startswith() and Slicing
The startswith() method checks if a string starts with a given prefix and returns True or False. Combined with string slicing, we can remove the prefix ?
text = "Red pen"
prefix = "Red"
if text.startswith(prefix):
result = text[len(prefix):]
print("After deleting the prefix:", result)
else:
print("Prefix not found")
After deleting the prefix: pen
Method 2: Using lstrip()
The lstrip() method removes specified characters from the beginning of a string. However, it removes individual characters, not the exact substring ?
text = "The sky is blue in color"
prefix_chars = "The"
result = text.lstrip(prefix_chars)
print("After using lstrip():", result)
After using lstrip(): sky is blue in color
Method 3: Using removeprefix() (Python 3.9+)
Python 3.9 introduced the removeprefix() method, which removes the exact prefix substring if it exists ?
text = 'qwertyuiop'
result = text.removeprefix('qwe')
print("After removing prefix:", result)
After removing prefix: rtyuiop
Method 4: Custom Function
You can create a custom function to handle prefix removal for older Python versions ?
def remove_prefix(original_string, prefix):
if original_string.startswith(prefix):
return original_string[len(prefix):]
else:
return original_string
text = 'abcdefghijklmnopqrstuvwxyz'
result = remove_prefix(text, 'abcdefghijkl')
print('Original string:', text)
print('After removing prefix:', result)
Original string: abcdefghijklmnopqrstuvwxyz After removing prefix: mnopqrstuvwxyz
Comparison of Methods
| Method | Python Version | Removes Exact Prefix? | Best For |
|---|---|---|---|
startswith() + slicing |
All versions | Yes | Custom logic needed |
lstrip() |
All versions | No (removes individual chars) | Removing character sets |
removeprefix() |
3.9+ | Yes | Modern Python versions |
| Custom function | All versions | Yes | Reusable code |
Conclusion
Use removeprefix() for Python 3.9+ as it's the most straightforward method. For older versions, combine startswith() with slicing or create a custom function. Avoid lstrip() when you need to remove exact prefixes rather than individual characters.
