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
Write a Python program to remove a certain length substring from a given string
We need to write a Python program that removes a specific substring from a given string. Python provides several methods to accomplish this task efficiently.
Algorithm
Step 1: Define a string. Step 2: Use the replace() function to remove the substring from the given string. Step 3: Display the modified string.
Using replace() Method
The most straightforward approach is using the built-in replace() method to replace the unwanted substring with an empty string ?
original_string = "C++ is a object oriented programming language"
modified_string = original_string.replace("object oriented", "")
print("Original:", original_string)
print("Modified:", modified_string)
Original: C++ is a object oriented programming language Modified: C++ is a programming language
Removing Multiple Occurrences
You can specify how many occurrences to remove using the count parameter ?
text = "Python is great. Python is powerful. Python is easy."
result = text.replace("Python", "Java", 2)
print("Original:", text)
print("Modified:", result)
Original: Python is great. Python is powerful. Python is easy. Modified: Java is great. Java is powerful. Python is easy.
Using split() and join()
Another method splits the string at the substring and joins the parts ?
original_string = "Hello world beautiful world"
substring_to_remove = "world"
parts = original_string.split(substring_to_remove)
result = "".join(parts)
print("Original:", original_string)
print("Modified:", result)
Original: Hello world beautiful world Modified: Hello beautiful
Parameters of replace() Method
The built-in Python replace() function accepts the following parameters:
- old: The substring you want to remove or replace
- new: The new string to replace the old substring (use empty string "" to remove)
- count: Optional. Maximum number of occurrences to replace
Comparison
| Method | Use Case | Advantages |
|---|---|---|
replace() |
Simple removal/replacement | Built-in, efficient, easy to use |
split() + join() |
Complex string manipulation | More control over the process |
Conclusion
The replace() method is the most efficient way to remove substrings from strings in Python. Use the count parameter to control how many occurrences to remove, or combine with other string methods for more complex operations.
