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

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

    You could do this:

    import re
    import string
    set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}
    
    for x in set1:
        x.replace('.good',' ')
        x.replace('.bad',' ')
        x = re.sub('\.good$', '', x)
        x = re.sub('\.bad$', '', x)
        print(x)
    
    0 讨论(0)
  • 2020-12-07 12:34

    I did the test (but it is not your example) and the data does not return them orderly or complete

    >>> ind = ['p5','p1','p8','p4','p2','p8']
    >>> newind = {x.replace('p','') for x in ind}
    >>> newind
    {'1', '2', '8', '5', '4'}
    

    I proved that this works:

    >>> ind = ['p5','p1','p8','p4','p2','p8']
    >>> newind = [x.replace('p','') for x in ind]
    >>> newind
    ['5', '1', '8', '4', '2', '8']
    

    or

    >>> newind = []
    >>> ind = ['p5','p1','p8','p4','p2','p8']
    >>> for x in ind:
    ...     newind.append(x.replace('p',''))
    >>> newind
    ['5', '1', '8', '4', '2', '8']
    
    0 讨论(0)
  • 2020-12-07 12:35

    All you need is a bit of black magic!

    >>> a = ["cherry.bad","pear.good", "apple.good"]
    >>> a = list(map(lambda x: x.replace('.good','').replace('.bad',''),a))
    >>> a
    ['cherry', 'pear', 'apple']
    
    0 讨论(0)
  • 2020-12-07 12:36

    if you delete something from list , u can use this way : (method sub is case sensitive)

    new_list = []
    old_list= ["ABCDEFG","HKLMNOP","QRSTUV"]
    
    for data in old_list:
         new_list.append(re.sub("AB|M|TV", " ", data))
    
    print(new_list) // output : [' CDEFG', 'HKL NOP', 'QRSTUV']
    
    0 讨论(0)
提交回复
热议问题