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
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.
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"