Search code examples
pythonstringintersection

Python - Intersectiing strings


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 tried:

def strIntersection(str1, str2):
    for i in str1:
        str3 = ''
        str3 = str3.join(i for i in str1 if i in str2 not in str3)
    return str3

str1 = 'asdfasdfasfd'
str2 = 'qazwsxedc'

strIntersection(str1,str2)

=> 'asdasdasd'

however I only want the the intersection characters to appear once and in order of the first string ie. 'asd'

Can anyone help?

I've found some similar problems on other forums but the solutions all seem to involve lists whereas I'd like my output to be a string


Solution

  • Check for occurances the other way around to get the order under control, and don't emit characters you've already emitted:

    def strIntersection(s1, s2):
      out = ""
      for c in s1:
        if c in s2 and not c in out:
          out += c
      return out
    

    Sure you could re-write it to be a list comprehension, but I find this easier to understand.

    For your test data, we get:

    >>> strIntersection('asdfasdfasfd' , 'qazwsxedc')
    'asd'