Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I modify my code such that it searches for all possible combinations till there’s no match left? Recurssion 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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading