Merging two strings with Suffix and Prefix using Python

String manipulation often necessitates merging two strings based on shared suffix and prefix sequences; suffices to be at the end, prefixes being at its beginning. This article will show how to merge two strings with suffixes and prefixes using Python language. We are considering two examples where we have two strings and their beginning and ending strings overlapped, the goal is to merge these by appending both strings together without creating redundant overlapped sections. As a result, there will be one string that contains all characters from both original strings without unnecessary duplication or repetition. In the second example, we use string concatenation and return a merged string.

Merging two Strings With Suffix and Prefix Using Python

Code Explanation and Design Steps −

  • Step 1 − Open Jupyter Notebook in Anaconda prompt and start writing the code in its cell.

  • Step 2 − Define a Merging Function, call the ‘merge_strings’ function with two arguments (st1 and st2). Take two strings as input and returns a combined version.

  • Step 3 − Determine minimum overlap length, this function will perform to calculate the maximum possible length of overlapping part. This length represents a shorter string since an overlap cannot exceed any string in length using the built-in ‘min’ function to find this shorter distance between s1 and s2.

  • Step 4 − Iterate over possible overlap lengths, iteration over all possible lengths of overlap from its maximum value calculated in Step 2 down to zero is done using a ‘for’ loop with range function with start as maximum overlap length, stop (inclusion of zero in loop), ‘step =-1’ as decrease length at every iteration is taken as well.

  • Step 5 − Check whether the suffix of one string matches that of another, Within each iteration of the loop, for every length ‘i’, we examine whether the last ‘i’ characters of ‘st1’ match those from ‘st2’. To perform this operation we employ Python's ends with string method and slicing.

  • Step 6 − If ‘suffix’ and ‘prefix’ are equal, merge both strings and return the result. If ‘endswith’ returns true, we have found an overlap of length ‘i’, in such an instance we merge by appending any parts from ‘st2’ that do not overlap to ‘st1’. This process uses string concatenation (‘+’ operator) and slicing before returning our result and stopping the execution of this function.

  • Step 7 − If there's no overlap found, combine and return. When our loop completes without encountering an overlap (endswith always returns False), concatenating strings ‘st1’ and ‘st2’ together then returning their combined value is our final operation after this loop has completed and no return statements were encountered within it. This operation only executes after it completes successfully unless no return statement had previously been encountered within it.

  • Step 8 − Create two strings to merge. Before entering our function, we define two strings to combine as inputs to our function.

  • Step 9 − Call and print the function.

Example 1

Code for merging two strings −

def merge_strings(st1, st2):
   min_overlap_len = min(len(st1), len(st2))
   for i in range(min_overlap_len, -1, -1):
      if st1.endswith(st2[:i]):
         return st1 + st2[i:]
   return st1 + st2
# Example
str1 = 'hello world'
str2 = 'world peace'
print(merge_strings(str1, str2))


After running the above code, the result shows on the console as Hello world peace

hello world peace

Merging two Strings With Suffix and Prefix Using String Concatenation

Code Explanation and Design Steps −

  • Step 1 − Open Jupyter Notebook in Anaconda prompt and start writing the code in its cell.

  • Step 2 − Use the function merge_strings_with_suffix_and_prefix to take two Arguments such as ‘prefix’ and ‘suffix’. It concatenates the ‘prefix’ and ‘suffix’ strings using the ‘+’ operator and returns the merged string.

  • Step 3 − Check the result.

Example 2

Code for merging two strings using string concatenation −

def merge_strings_with_suffix_and_prefix(prefix, suffix):
   merged_string = prefix + suffix
   return merged_string

# Example 
prefix = "Hello, "
suffix = "world!"
merged_string = merge_strings_with_suffix_and_prefix(prefix, suffix)


After running the above code, the result shows on the console as Hello, world!

Hello, world!


In this article, we can be merged two strings using Python language. We are taking two examples in order to understand the concept of merging strings. String manipulation is an indispensable aspect of data processing, bioinformatics (e.g. assembling DNA sequences), and text analysis - and is one key aspect of string manipulation that contributes significantly to text mining and natural language processing as a field. Though an essential task, Python's standard library lacks an inbuilt function for carrying out this operation, so we must find our own custom solution based on string handling capabilities combined with expressive syntax that enable the efficient development of an efficient solution.

Updated on: 18-Oct-2023


Kickstart Your Career

Get certified by completing the course

Get Started