Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two strings with a common substring?

Tags:

python

string

Say I have strings,

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

The result should be something like

Hello how are you doing now?

I was thinking different ways using re and string search. (Longest common substring problem)

But is there any simple way (or library) that does this in python?

To make things clear i'll add one more set of test strings!

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

the result would be!,

'This is a nice ACADEMY you know!'
like image 458
void Avatar asked Sep 20 '25 20:09

void


1 Answers

This should do:

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

or, make it a function so that you can use it again without rewriting:

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!'
like image 115
Ashish Ranjan Avatar answered Sep 22 '25 08:09

Ashish Ranjan