String or tuple and unions

Alex Martelli aleax at aleax.it
Sun Feb 9 16:59:25 EST 2003


Grumfish wrote:
   ...
> Two more questions, is there a way to find the union of two sets? And

Since you've specified that the "set" is actually a string (presumably it
must have no duplicates), then yes, there's a very fast way:

import string
identity = string.maketrans('', '')

def union(astring, another):
    return astring+another.translate(identity, astring)


The translate method of string objects does both character translation
(here, none, since we pass it the identity table as the 1st argument)
AND deletion -- it removes all characters found in the 2nd argument.
And it's very fast.


Alex





More information about the Python-list mailing list