view raw
Vachan Bhat Vachan Bhat - 1 year ago 32
Python Question

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

I have a set of strings

, and all the strings in
have a two specific substrings which I don't need and want to remove.

Sample Input:

So basically I want the
substrings removed from all the strings.
What I tried:

for x in set1:

But this doesn't seem to work at all. There is absolutely no change in the output and it is the same as the input. I tried using
for x in list(set1)
instead of the original one but that doesn't change anything.


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

Return a copy of string s 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 set comprehension):

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