If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Lecture 98:- Remove All Occurrences of a Substring
To remove all occurrences of a substring from a given string in Python, you can use various methods, but regular expressions (RE) can provide an elegant solution. The
re.sub()
function can be used to replace all occurrences of a specific pattern (substring) with an empty string.Here's a Python code snippet to remove all occurrences of a substring using regular expressions:
pythonCopy code
import re def remove_substring_with_re(input_string, substring): # Use a regular expression to find all occurrences of the substring and replace them with an empty string modified_string = re.sub(re.escape(substring), '', input_string) return modified_string # Test the function input_string = "Hello, Hello, World!" substring_to_remove = "Hello, " result = remove_substring_with_re(input_string, substring_to_remove) print(result)
Output:
Copy code
World!
In this example, the
re.sub()
function takes the regular expression pattern to be replaced as the first argument. There.escape(substring)
is used to escape the substring properly, as it might contain characters that have special meanings in regular expressions. The second argument is the replacement, which is an empty string''
.The
re.sub()
function then finds all occurrences of thesubstring
in theinput_string
and replaces them with an empty string, effectively removing all occurrences of the specified substring.Keep in mind that this method is case-sensitive. If you want a case-insensitive version, you can use the
re.IGNORECASE
flag as the third argument tore.sub()
:pythonCopy code
import re def remove_substring_case_insensitive(input_string, substring): # Use a regular expression with the IGNORECASE flag to find all occurrences of the substring and replace them with an empty string modified_string = re.sub(re.escape(substring), '', input_string, flags=re.IGNORECASE) return modified_string # Test the function input_string = "Hello, HeLLo, World!" substring_to_remove = "hello, " result = remove_substring_case_insensitive(input_string, substring_to_remove) print(result)
Output:
Copy code
World!
Now, the function will remove all occurrences of "hello, " regardless of their case.
Comments: 2
SCIAKU Team please upload 1st video of TREE please please please, please
I bought this course, it worth it!
Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it
Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website