用一个公共子字符串连接两个字符串?

voi*_*oid 1 python string

说我有绳子,

string1 = 'Hello how are you'
string2 = 'are you doing now?'
Run Code Online (Sandbox Code Playgroud)

结果应该是这样的

Hello how are you doing now?
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用re和字符串搜索的不同方式。(最长公共子串问题

但是有没有什么简单的方法(或库)可以在 python 中做到这一点?

为了清楚起见,我将再添加一组测试字符串!

string1 = 'This is a nice ACADEMY'
string2 = 'DEMY you know!'
Run Code Online (Sandbox Code Playgroud)

结果是!,

'This is a nice ACADEMY you know!'
Run Code Online (Sandbox Code Playgroud)

Ash*_*jan 5

这应该做:

string1 = 'Hello how are you'
string2 = 'are you doing now?'
i = 0
while not string2.startswith(string1[i:]):
    i += 1

sFinal = string1[:i] + string2
Run Code Online (Sandbox Code Playgroud)

输出 :

>>> sFinal
'Hello how are you doing now?'
Run Code Online (Sandbox Code Playgroud)

或者,使其成为一个函数,以便您无需重写即可再次使用它:

def merge(s1, s2):
    i = 0
    while not s2.startswith(s1[i:]):
        i += 1
    return s1[:i] + s2
Run Code Online (Sandbox Code Playgroud)

输出 :

>>> merge('Hello how are you', 'are you doing now?')
'Hello how are you doing now?'
>>> merge("This is a nice ACADEMY", "DEMY you know!")
'This is a nice ACADEMY you know!'
Run Code Online (Sandbox Code Playgroud)