Python 中的字符串交集

String intersection in Python

这是我的代码:

keyinput = input() # I type 'appleandgold'

B = 'appleblue'

if keyinput in B: # Should actually be keyinput "intersects" B   
     print(keyinput) # Should print intersection

keyinput = 'appleandgold'B = 'appleblue' 的结果(打印值)应该是 'apple',但我只能让它为 keyinput = 'apple' 工作。

您似乎在寻找最长的公共子串。标准库包含 difflib 模块:

from difflib import SequenceMatcher

keyinput = input()  # I type "appleandgold"

B = "appleblue"

match = SequenceMatcher(a=keyinput, b=B).find_longest_match(
    0,
    len(keyinput),
    0,
    len(B),
)
print(keyinput[match.a:match.a+match.size])  # prints "apple"

您可以在不导入任何模块的情况下尝试这样的操作:

s1='appleandgold'
s2='appleblue'

track=[]
for k in range(len(s1)):
    if k!=0:
        for ka in range(0,len(s1),k):
            if s1[ka:ka+k] in s2:
                track.append((len(s1[ka:ka+k]),s1[ka:ka+k]))
print(max(track)[1])

输出:

apple