0

I am sure there is a better way to describe my problem (hence why I haven't found much on google), but I want to compare two separate strings and pull the substrings they have in common.

Say I have a function that takes two arguments, "hello,world,pie" and "hello,earth,pie"

I want to return "hello,pie"

How could I do this? Here is what I have so far

def compare(first, second):
    save = []
    for b, c in set(first.split(',')), set(second.split(',')):
        if b == c:
             save.append(b)




compare("hello,world,pie", "hello,earth,pie")
Nick Kremer
  • 163
  • 1
  • 1
  • 5

4 Answers4

0

try like this:

>>> def common(first, second):
...     return list(set(first.split(',')) & set(second.split(',')))
... 
>>> common("hello,world,pie", "hello,earth,pie")
['hello', 'pie']
Hackaholic
  • 17,534
  • 3
  • 51
  • 68
0
>>> a = "hello,world,pie"
>>> b = "hello,earth,pie"
>>> ','.join(set(a.split(',')).intersection(b.split(',')))
'hello,pie'
jamylak
  • 120,885
  • 29
  • 225
  • 225
0

try this

a="hello,world,pie".split(',')
b="hello,earth,pie".split(',')

print  [i for i in a if i in b]
Ash
  • 345
  • 1
  • 2
  • 7
0

use set() & set():

def compare(first, second):
    return ','.join(set(first.split(',')) & set(second.split(','))) 

compare("hello,world,pie", "hello,earth,pie")
'hello,pie'
Anzel
  • 18,599
  • 5
  • 46
  • 51