gpt4 book ai didi

python - 将两个字符串与一个公共(public)子字符串连接起来?

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:33 24 4
gpt4 key购买 nike

假设我有字符串,

string1 = 'Hello how are you'
string2 = 'are you doing now?'

结果应该是这样的

Hello how are you doing now?

我在考虑使用 re 和字符串搜索的不同方式。(Longest common substring problem)

但是在 python 中是否有任何简单的方法(或库)可以做到这一点?

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

string1 = 'This is a nice ACADEMY'
string2 = 'DEMY you know!'

结果会是!

'This is a nice ACADEMY you know!'

最佳答案

应该这样做:

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

sFinal = string1[:i] + string2

输出:

>>> sFinal
'Hello how are you doing now?'

或者,让它成为一个函数,这样你就可以在不重写的情况下再次使用它:

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

输出:

>>> 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!'

关于python - 将两个字符串与一个公共(public)子字符串连接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com