Home > Blockchain >  Concatenate strings with a common substring in python?
Concatenate strings with a common substring in python?

Time:09-27

Input

ONESTRING
STRINGTHREE
THREEFOUR 
FOURFIVE

Output

ONESTRINGTHREEFOURFIVE

in python??

I think first i concatenate with 2 string then run a loop but this gives an error I don't know why can anyone help in in python?

CodePudding user response:

Assuming your strings to join are in order (i.e., the first pair matches, the second pair matches, etc.),

"".join(strings).replace("STRING", "", 1).replace("THREE", "", 1).replace("FOUR", "", 1)

CodePudding user response:

Here is generic solution according your provided example. Sequence must be ordered, other wise it will not work.

from functools import reduce
s = [
"ONESTRING",
"STRINGTHREE",
"THREEFOUR",
"FOURFIVE",
]


def join_f(first, add):
    i = 1
    while add[:i] in first:
        i  = 1
    return first   add[i-1:]

print(reduce(join_f, s))

CodePudding user response:

May use difflib library, sample code for your reference

from difflib import SequenceMatcher

str1 = "ONESTRING"
str2 = "STRINGTHREE"

match = SequenceMatcher(None, str1, str2).find_longest_match(0, len(str1), 0, len(str2))
#match[a]=3, match[b]=0, match[size]=6
  • Related