Bob
Bob

Reputation: 289

removing common string elements in two sets python3

I am trying to figure out how to remove the common values in two sets.

set1={":dog","cat","mouse"}
set2={"bird","dog","house","fish"}

So the result is just {"cat","mouse","bird","house","fish"}.

I was looking on stack overflow and found this Removing the common elements between two lists but I'm not sure if it's specific to numbers or like the old python format because it wasn't working.

In my code I first got rid of the : in set1 by doing

line = re.sub('[:]', '', str(set1))

then I did :

res=list(set(line)^set(set2))

and I also tried

res=list(line^set2)

but the output is very strange it's

[',', 'u', 'c', '{', "'", 'o', 's', 'g', 'house', 'd', 't', 'bird', 'fish', 'm', 'dog', 'a', 'e', ' ', '}']

Upvotes: 1

Views: 132

Answers (1)

jpp
jpp

Reputation: 164773

There are a few way:

set1 = {":dog", "cat", "mouse"}
set2 = {"bird", "dog", "house", "fish"}

set1 = {k.replace(':', '') for k in set1}

# 3 equivalent methods

set1 ^ set2
set1.symmetric_difference(set2)
(set1 | set2) - (set1 & set2)

# {'bird', 'cat', 'fish', 'house', 'mouse'}

Upvotes: 2

Related Questions