Python - Add Phrase in middle of String
Last Updated :
12 May, 2023
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))
OutputThe 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))
OutputThe 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)))
OutputThe 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:
- Initialize the original string and the phrase to be added in the middle of the string.
- Split the string into words using the split() method.
- Calculate the middle position by integer dividing the length of the resulting list by 2.
- 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.
- 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.
- 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))
OutputThe 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))
OutputThe 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.
- Initialize the string test_str with the value 'geekforgeeks is for geeks'.
- Print the original string using print("The original string is : " + str(test_str)).
- Initialize the string mid_str with the value 'best'.
- Split the original string test_str into a list of words using words = test_str.split().
- Calculate the middle index of the list words using mid_pos = len(words) // 2.
- 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:
- Print the formulated string using print("Formulated String : " + str(res)).
- 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))
OutputThe 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
Similar Reads
Find Length of String in Python
In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop.
2 min read
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.Using str.find() The find() method searches for the first occurrence of the specified substring and return
3 min read
Python - Phrase removal in String
Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
2 min read
List of strings in Python
A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples.Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings.Pythona =
2 min read
Iterate over words of a String in Python
In this article, weâll explore different ways to iterate over the words in a string using Python.Let's start with an example to iterate over words in a Python string:Pythons = "Learning Python is fun" for word in s.split(): print(word)OutputLearning Python is fun Explanation: Split the string into w
2 min read
Python | Add one string to another
The concatenation of two strings has been discussed multiple times in various languages. But the task is how to add to a string in Python or append one string to another in Python. Example Input: 'GFG' + 'is best' Output: 'GFG is best' Explanation: Here we can add two string using "+" operator in Py
5 min read
Insert a number in string - Python
We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
In-Place String Modifications in Python
Strings are immutable in Python, meaning their values cannot be modified directly after creation. However, we can simulate in-place string modifications using techniques such as string slicing and conversion to mutable data types like lists.Using String SlicingString slicing is one of the most effic
2 min read
How to Find Index of a Substring in Python
In Python, sometimes we need to know where a certain substring appears in a string. To do this, we can find the index (or position) of that substring. The index tells us where the substring is located. Letâs look at some simple ways to find the index of a substring in a string.Using find() methodThe
2 min read
Python - Line Break in String
Line Break helps in making the string easier to read or display in a specific format. When working with lists, the join() method is useful, and formatted strings give us more control over our output.Using \n for new line The simplest way to add a line break in a string is by using the special charac
2 min read