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

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

    Strings are immutable. string.replace (python 2.x) or str.replace (python 3.x) 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}
    

提交回复
热议问题