Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce a string by another string in Python?

Tags:

python

string

I would like to remove all characters from a first string s1 exactly the number of times they appear in another string s2, i.e. if s1 = "AAABBBCCCCCCD" and s2 = "ABBCCC" then the result should be s = "AABCCCD". (The order of the characters in the resulting string is actually irrelevant but it's a plus if it can be preserved.)

The following rather crude code can do this:

def reduce_string(s1, s2):
    s = s1
    for c in s2:
        if c in s:
            s = s.replace(c, "", 1)
    return(s)

# examples
reduce_string("AAABBBCCCCCCD", "ABBCCC")
reduce_string("AAABBBCCCCCCD", "ABBCCCE")

My question is, can the same be achieved by clever use of some built-in function or at least in a more elegant way? Thank you for all your answers!

like image 656
schotti Avatar asked Mar 02 '23 09:03

schotti


1 Answers

You can use counter objects. Subtract one against the other and join the remaining elements together.

from collections import Counter

s1 = "AAABBBCCCCCCD"
s2 = "ABBCCC"

counter = Counter(s1)
counter.subtract(Counter(s2))

result = ''.join(counter.elements())
print(result)
AABCCCD

As a one-liner:

print(''.join((Counter(s1) - Counter(s2)).elements()))
like image 190
flakes Avatar answered Mar 03 '23 22:03

flakes