Skip to content
Related Articles

Related Articles

Python – Add Phrase in middle of String

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 16 Aug, 2022
View Discussion
Improve Article
Save Article

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)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!