Open In App

Python – Add Phrase in middle of String

Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, add a phrase in the middle of it.

Input : test_str = ‘geekforgeeks is for geeks’, mid_str = “good” 
Output : geekforgeeks is good for geeks 
Explanation : Added just in middle, after 2 words.

Input : test_str = ‘geekforgeeks best’, mid_str = “is” 
Output : geekforgeeks is best 
Explanation : Added just in middle, after 1 word. 

Method #1 : Using split() + slicing + join()

In this, Strings are converted to a list of words, then the middle position is extracted to append a new phrase. After addition, the string is back converted using join().

Python3




# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
 
# initializing string
test_str = 'geekforgeeks is for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing mid string
mid_str = "best"
 
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 2
 
# appending in mid
res = temp[:mid_pos] + [mid_str] + temp[mid_pos:]
 
# conversion back
res = ' '.join(res)
 
# printing result
print("Formulated String : " + str(res))


Output

The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks

Time Complexity: O(n), as ‘join’ and slicing takes O(n)
Auxiliary Space: O(n)

Method #2 : Using split() + slicing + join() [ more compact]

Similar to the above method, just a one-liner way to solve this problem, for more compact.

Python3




# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
 
# initializing string
test_str = 'geekforgeeks is for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing mid string
mid_str = "best"
 
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 2
 
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
 
# printing result
print("Formulated String : " + str(res))


Output

The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks

Time Complexity: O(n), as ‘join’ and slicing takes O(n)
Auxiliary Space: O(n)

Method #3 : Using insert()

In this method, we insert the new phrase in the middle of the string by using the insert() method.

Python3




# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using insert()
 
 
# initializing string
test_str = 'geekforgeeks is for geeks'
# printing original string
print("The original string is : " + str(test_str))
test=test_str.split()
# initializing mid string
mid_str = "best"
# finding middle word
mid_pos = len(test) // 2
test.insert(mid_pos,mid_str)
# printing result
print("Formulated String : " + str(" ".join(test)))


Output

The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks

Time Complexity: O(n), as insert() takes O(n) 
Auxiliary Space: O(n)

Method#4 using re module 

Approach:

  1. Initialize the original string and the phrase to be added in the middle of the string.
  2. Split the string into words using the split() method.
  3. Calculate the middle position by integer dividing the length of the resulting list by 2.
  4. Add the phrase in the middle of the string using list slicing, and join the resulting list back into a string using the join() method.
  5. Alternatively, use an f-string to concatenate the parts of the string, or use regular expressions to replace the first occurrence of whitespace with the phrase.
  6. Print the original string and the resulting string.

Python3




import re
 
# original string to add phrase in the middle
test_str = 'geekforgeeks is for geeks'
 
# phrase to add in the middle
mid_str = 'best'
 
# split the string into words and calculate the middle position
words = test_str.split()
mid_pos = len(words) // 2
 
# add the phrase in the middle of the string
res = ' '.join(words[:mid_pos] + [mid_str] + words[mid_pos:])
 
# Alternatively, we can use f-string to concatenate the string parts:
# res = f"{test_str[:mid_pos]}{mid_str} {test_str[mid_pos+1:]}"
 
# using regex to replace first occurrence of whitespace with the phrase
# res = re.sub(r'\s', f' {mid_str} ', test_str, count=1)
 
# print the original string and the resulting string
print("The original string is : " + str(test_str))
print("The formulated string is : " + str(res))


Output

The original string is : geekforgeeks is for geeks
The formulated string is : geekforgeeks is best for geeks

Time complexity O(n), where n is the length of the original string. This is because splitting the string into words, slicing the list, and joining the list all take linear time proportional to the length of the string.

Auxiliary space: O(n), where n is the length of the original string. This is because splitting the string into words and creating a new list to hold the resulting words all take up space proportional to the length of the string.

Tip: The space complexity can be reduced to O(1) by using an in-place algorithm to modify the original string directly, but this may be less readable and more error-prone.

Method #5: Using string concatenation

Steps:

Initialize the original string and the mid string.
Split the original string into a list of words.
Determine the middle position of the list using integer division.
Concatenate the words before the middle position with the mid string, followed by the words after the middle position.
Print the formulated string.

Python3




# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using string concatenation
 
# initializing string
test_str = 'geekforgeeks is for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing mid string
mid_str = "best"
 
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 2
 
# concatenating strings
res = ' '.join(temp[:mid_pos]) + ' ' + mid_str + ' ' + ' '.join(temp[mid_pos:])
 
# printing result
print("Formulated String : " + str(res))


Output

The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks

Time complexity: O(n), where n is the length of the original string.
Auxiliary space: O(n), where n is the length of the original string.

Method 6: Using list comprehension and join the resulting list with a space character.

  1. Initialize the string test_str with the value ‘geekforgeeks is for geeks’.
  2. Print the original string using print(“The original string is : ” + str(test_str)).
  3. Initialize the string mid_str with the value ‘best’.
  4. Split the original string test_str into a list of words using words = test_str.split().
  5. Calculate the middle index of the list words using mid_pos = len(words) // 2.
  6. Create a new list new_words using a list comprehension that adds the mid_str at the mid_pos index while copying the rest of the words from the original list words. Here’s the code that does this:
  7. Print the formulated string using print(“Formulated String : ” + str(res)).
  8. This program splits the original string into a list of words, adds the mid_str at the middle index, and then joins the list back into a string.

Python3




# initializing string
test_str = 'geekforgeeks is for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing mid string
mid_str = "best"
 
# splitting the string into words
words = test_str.split()
 
# calculating the middle index
mid_pos = len(words) // 2
 
# inserting the mid string at the middle index
words.insert(mid_pos, mid_str)
 
# joining the list with space character to form the new string
res = ' '.join(words)
 
# printing result
print("Formulated String : " + str(res))


Output

The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks

Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(n), where n is the length of the string



Last Updated : 12 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads