Trying to write a for function that takes two strings and returns the characters that intersect in the order that they appear in the first string.
Here\'s what I tri
You want a string consisting of the unique characters that are common to str1
and str2
, in the order they appear in str1
.
Uniqueness and commonality imply set operations: that is, we're looking for the set of characters that appear in both str1 and str2. A set is fundamentally unordered, but we can re-order the data by sorting the characters according to their "index" of first occurrence in str1
. Then it's a simple matter of creating a string from the sorted sequence.
Putting it all together, we get:
''.join(sorted(set(str1) & set(str2), key = str1.index))