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

后端 未结 10 1941
自闭症患者
自闭症患者 2020-12-07 12:08

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

10条回答
  •  我在风中等你
    2020-12-07 12:25

    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'}
    

提交回复
热议问题