How to remove specific substrings from a set of strings in Python? [duplicate]

Strings are immutable. str.replace creates a new string. This is stated in the documentation:

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. […]

This means you have to re-allocate the set or re-populate it (re-allocating is easier with a set comprehension):

new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}

P.S. if you want to change the prefix or suffix of a string and you’re using Python 3.9 or newer, use str.removeprefix() or str.removesuffix() instead:

new_set = {x.removesuffix('.good').removesuffix('.bad') for x in set1}

Leave a Comment