我确信有更好的方式来描述我的问题(因此我没有在谷歌上发现很多),但我想比较两个单独的字符串并拉出他们共同的子串。
假设我有一个带有两个参数的函数"hello,world,pie"
和"hello,earth,pie"
我想要返回"hello,pie"
我怎么能这样做?这是我到目前为止所拥有的
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")
答案 0 :(得分:0)
尝试这样:
>>> def common(first, second):
... return list(set(first.split(',')) & set(second.split(',')))
...
>>> common("hello,world,pie", "hello,earth,pie")
['hello', 'pie']
答案 1 :(得分:0)
>>> a = "hello,world,pie"
>>> b = "hello,earth,pie"
>>> ','.join(set(a.split(',')).intersection(b.split(',')))
'hello,pie'
答案 2 :(得分:0)
试试这个
a="hello,world,pie".split(',')
b="hello,earth,pie".split(',')
print [i for i in a if i in b]
答案 3 :(得分:0)
使用 set()&集()强>:
def compare(first, second):
return ','.join(set(first.split(',')) & set(second.split(',')))
compare("hello,world,pie", "hello,earth,pie")
'hello,pie'