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
  • 213
  • 1
  • 2
  • 6

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
  • 19,069
  • 5
  • 54
  • 72
0
>>> a = "hello,world,pie"
>>> b = "hello,earth,pie"
>>> ','.join(set(a.split(',')).intersection(b.split(',')))
'hello,pie'
jamylak
  • 128,818
  • 30
  • 231
  • 230
0

try this

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

print  [i for i in a if i in b]
Ash
  • 355
  • 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
  • 19,825
  • 5
  • 51
  • 52