I have a set of strings set1, and all the strings in set1 have a two specific substrings which I don\'t need and want to remove.
Sample Input
Update for Python 3.9
In python 3.9 you could remove suffix using str.removesuffix('suffix')
From the docs,
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string:
set1 = {'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}
set2 = set()
for s in set1:
set2.add(s.removesuffix(".good").removesuffix(".bad"))
or using set comprehension:
set2 = {s.removesuffix(".good").removesuffix(".bad") for s in set1}
print(set2)
Output:
{'Orange', 'Pear', 'Apple', 'Banana', 'Potato'}