Python - Intersectiing strings

前端 未结 6 598
北海茫月
北海茫月 2021-01-18 08:26

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

6条回答
  •  旧时难觅i
    2021-01-18 08:48

    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))
    

提交回复
热议问题