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

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

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}
>>> x = Pear.good
>>> y = x.replace(.good,)
>>> y
Pear
>>> x
Pear.good

.replace doesnt change the string, it returns a copy of the string with the replacement. You cant change the string directly because strings are immutable.

You need to take the return values from x.replace and put them in a new set.

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

All you need is a bit of black magic!

>>> a = [cherry.bad,pear.good, apple.good]
>>> a = list(map(lambda x: x.replace(.good,).replace(.bad,),a))
>>> a
[cherry, pear, apple]

Leave a Reply

Your email address will not be published. Required fields are marked *