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

后端 未结 10 1934
自闭症患者
自闭症患者 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:27

    When there are multiple substrings to remove, one simple and effective option is to use re.sub with a compiled pattern that involves joining all the substrings-to-remove using the regex OR (|) pipe.

    import re
    
    to_remove = ['.good', '.bad']
    strings = ['Apple.good','Orange.good','Pear.bad']
    
    p = re.compile('|'.join(map(re.escape, to_remove))) # escape to handle metachars
    [p.sub('', s) for s in strings]
    # ['Apple', 'Orange', 'Pear']
    

提交回复
热议问题