How to subtract two strings?

后端 未结 8 2039
执笔经年
执笔经年 2020-12-30 00:53

I have a long string, which is basically a list like str=\"lamp, bag, mirror,\" (and other items)

I was wondering if I can add or subtract some items, i

相关标签:
8条回答
  • 2020-12-30 01:21
    from re import sub
    
    def Str2MinusStr1 (str1, str2, n=1) :
        return sub(r'%s' % (str2), '', str1, n)
    
    Str2MinusStr1 ('aabbaa', 'a')  
    # result 'abbaa'
    
    Str2MinusStr1 ('aabbaa', 'ab')  
    # result 'abaa'
    
    Str2MinusStr1 ('aabbaa', 'a', 0)  
    # result 'bb'
    
    # n = number of occurences. 
    # 0 means all, else means n of occurences. 
    # str2 can be any regular expression. 
    
    0 讨论(0)
  • 2020-12-30 01:24

    Using the following you can add more words to remove (["bag", "mirror", ...])

    (s0, to_remove) = ("lamp, bag, mirror", ["bag"])
    s0 = ", ".join([x for x in s0.split(", ") if x not in to_remove])
    => "lamp, mirror"
    
    0 讨论(0)
提交回复
热议问题