说我有弦,
string1 = 'Hello how are you'
string2 = 'are you doing now?'
结果应该是这样的
Hello how are you doing now?
我正在考虑使用不同的方式re
和字符串搜索。
(最长公共子串问题 http://en.wikipedia.org/wiki/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
OUTPUT :
>>> 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
OUTPUT :
>>> 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!'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)