Search code examples
pythonpython-3.xstringreplace

Remove all sub-strings from a string


I have a string from which I want to remove all possible combinations till the end.

I tried this:

combinations = ['XY', 'ZU', 'YY']
lst_matched = list(filter(lambda val: val in mystring, combinations))
for i in matches:
    if len(mystring) > 0:
        mystring = mystring.replace(i,'')
        print('after', mystring)

If I use this with a mystring like ZXYUYY, it will identify lst_matched as [XY, YY] and my function will correctly remove these substrings from mystering.

However, after removing these substrings, the updated string now has ZUwhich is also another combination to check for.

How can I modify my code such that it searches for all possible combinations till there's no match left? Recursion could be used but not sure how.


Solution

  • Try this:

    def replace(mystring, combinations):
        val = next((val for val in combinations if val in mystring), None)
        while val is not None:
            mystring = mystring.replace(val, '')
            val = next((val for val in combinations if val in mystring), None)
        return mystring
    

    Basically you find the first combination that can be found in mystring (this can be done with next((val for val in combinations if val in mystring), None)). If no such a combination can be found then val will be None.

    Then you replace that specific combination with ''. And you repeat. You stop when such combination cannot be found anymore (i.e., when val is None).

    Examples:

    >>> replace('ZXYUYY', ['XY', 'ZU', 'YY'])
    ''
    >>> replace('ZXYUYY', ['XY', 'YY'])
    'ZU'
    >>> replace('AZXYUYY', ['XY', 'ZU', 'YY'])
    'A'
    >>> replace('AZBXYUYY', ['XY', 'ZU', 'YY'])
    'AZBU'