DEV Community

joshua-brown0010
joshua-brown0010

Posted on

Python Remove Substring How to Remove a Substring from a String in Python?

A substring is a chain of sequential characters inside a bigger string. Removing a substring from a fixed of strings deletes this substring from every detail within the set.Use str.replace() inside a for-loop to get rid of a substring from all strings in a fixed set of strings.

Use str.replace(old, new) with new as "" to remove substring old from str.

_string = "programming"

new_string = a_string.replace("ing", "")


print(new_string)

Output

programm
Enter fullscreen mode Exit fullscreen mode

Use str.replace() in a for-loop to remove a substring from all elements in the set. Add each modified string to a new set.

string_set = {"learning", "enjoying", "programming"}

new_set = set()


for a_string in string_set:

    new_string = a_string.replace("ing", "")

    new_set.add(new_string)


print(new_set)

Output

{'enjoy', 'learn', 'programm'}
Enter fullscreen mode Exit fullscreen mode

Use a set comprehension for a more compact implementation.

string_set = {"learning", "enjoying", "programming"}

new_set = {x.replace("ing", "") for x in string_set}


print(new_set)

Output

{'enjoy', 'learn', 'programm'}
Enter fullscreen mode Exit fullscreen mode

Warning

sets are an unordered collection of items. Performing set comprehensions does not preserve the original ordering.

Remove a prefix from a string

Is there a fashionable manner to remove a substring from the start of a string? Replacing the string root withinside the given course rigorously ought to update later occurrences as well, successfully returning nonsense, because the feedback pointed out. I could propose to update the start of the string properly:

import re end result = re.sub(r'^' + re.escape(root), '', course)
This manner you keep away from each error loops.

Starting in Python 3.9 , you could use :
Read more

Top comments (0)