Open In App

Python – Add Space between Potential Words

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given list of Strings, task is to add a space before sequence which begin with capital letters.

Input : test_list = [“gfgBest”, “forGeeks”, “andComputerScienceStudents”] 
Output : [‘gfg Best’, ‘for Geeks’, ‘and Computer Science Students’] 
Explanation : Words segregated by Capitals.

Input : test_list = [“ComputerScienceStudentsLoveGfg”] 
Output : [‘Computer Science Students Love Gfg’] 
Explanation : Words segregated by Capitals. 
 

Method #1 : Using loop + join()

 This is one of the ways in which this task can be performed. In this, we perform the task of iterating all the strings and then all the characters before adding space using loop in brute force manner. The isupper() is used to check for capital character.

Python3




# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using loop + join()
 
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
 
# printing original list
print("The original list : " + str(test_list))
 
res = []
 
# loop to iterate all strings
for ele in test_list:
    temp = [[]]
    for char in ele:
         
        # checking for upper case character
        if char.isupper():
            temp.append([])
             
        # appending character at latest list
        temp[-1].append(char)
     
    # joining lists after adding space
    res.append(' '.join(''.join(ele) for ele in temp))
 
# printing result
print("The space added list of strings : " + str(res))


Output

The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']

The time complexity of the code is O(nm), where n is the number of strings in the list and m is the average length of the strings. The reason for this is that for each string in the list, the code needs to iterate through its characters and check if it is an upper case character. This takes O(m) time for each string.
The space complexity is O(nm) because of the use of multiple lists to store intermediate results.

Method #2 : Using regex() + list comprehension

The combination of above functions can also be used to solve this problem. In this we employ regex code to check for upper case letters and perform space addition and joining using list comprehension.

Python3




# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using regex() + list comprehension
import re
 
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
 
# printing original list
print("The original list : " + str(test_list))
 
# using regex() to perform task
res = [re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in test_list]
 
# printing result
print("The space added list of strings : " + str(res))


Output

The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']

Time Complexity: O(n) where n is the number of elements in the list “test_list”. The re.sub() function is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”. The re.sub() function creates a new string for each element in the list and hence consumes O(n) space.

Method #3 : Using  isupper() and replace() methods

The combination of above functions can also be used to solve this problem. In this we check for any uppercase character using isupper() function and then add an additional space with the use of replace() function.

Python3




# Python3 code to demonstrate working of
# Add Space between Potential Words
 
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
 
# printing original list
print("The original list : " + str(test_list))
 
res = []
for i in test_list:
    for j in i:
        if(j.isupper()):
            i = i.replace(j, " "+j)
    res.append(i)
 
# printing result
print("The space added list of strings : " + str(res))


Output

The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”. 

Method #4 : Using loop, without any builtin methods

Python3




# Python3 code to demonstrate working of
# Add Space between Potential Words
 
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
 
# printing original list
print("The original list : " + str(test_list))
 
res = []
alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in test_list:
    s=""
    for j in i:
        if(j in alphabets):
            s+= " "+j
        else:
            s+=j
    res.append(s)
 
# printing result
print("The space added list of strings : " + str(res))


Output

The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']

Time Complexity : O(N)
Auxiliary Space : O(N)

Method #5 : Using add_space():

Python3




import re
def add_space(strings):
    return [re.sub(r'([A-Z][a-z]+)', r' \1', ele) for ele in strings]
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
  
result = add_space(test_list)
print("The space added list of strings:", result)
#This code is contributed by Jyothi pinjala


Output

The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings: ['gfg Best', 'for Geeks', 'and Computer Science']

Time Complexity : O(N^2)
Auxiliary Space : O(N)

Method 6 : using regular expressions and the re module. 

 step-by-step approach:

  • Import the re module.
  • Define a regular expression pattern to match one or more uppercase letters ([A-Z]+) followed by one or more lowercase letters ([a-z]+), separated by zero or more non-alphabetic characters ([^a-zA-Z]*).
  • Define a function add_space_regex(s) that uses the re.sub() method to replace all occurrences of the pattern with a space followed by the matched string (i.e., the potential word).
  • Define a list comprehension that applies the add_space_regex() function to each element of the input list test_list to obtain the list of spaced strings.
  • Print the original list and the list of spaced strings.

Python3




import re
 
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
 
# printing original list
print("The original list : " + str(test_list))
 
# define regular expression pattern
pattern = r'[A-Z]+[a-z]+[^a-zA-Z]*'
 
# define function to add spaces using regex
def add_space_regex(s):
    return re.sub(pattern, r' \g<0>', s).strip()
 
# apply function to each element of the list using list comprehension
res = [add_space_regex(s) for s in test_list]
 
# printing result
print("The space added list of strings : " + str(res))


Output

The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']

The time complexity of this approach is O(nm), where n is the number of strings in the input list and m is the maximum length of a string in the list.
The auxiliary space complexity is O(m), for storing the output list of spaced strings.

METHOD 7:Using defaultdict 

APPROACH:

This program takes an original list of strings as input and adds spaces between the potential words. The output is a modified list of strings.

ALGORITHM:

1.Iterate through each word in the original list
2.For each character in the word, check if it is uppercase
3.If it is uppercase, add a space to the previous character index in a defaultdict
4.Concatenate the values of the defaultdict and append it to the modified list
5.Print the modified list

Python3




from collections import defaultdict
 
original_list = ['gfgBest', 'forGeeks', 'andComputerScience']
modified_list = []
 
for word in original_list:
    d = defaultdict(str)
    for i, c in enumerate(word):
        if c.isupper():
            d[i] += ' '
        d[i] += c
    modified_list.append(''.join(d.values()))
 
print("The modified list:", modified_list)


Output

The modified list: ['gfg Best', 'for Geeks', 'and Computer Science']

Time complexity: O(n*m) where n is the length of the original list and m is the average length of each word in the list.
Space complexity: O(n*m) since a defaultdict is created for each word in the list, and each defaultdict may store multiple characters.



Similar Reads

Pollution Control by Identifying Potential Land for Afforestation - Python Project
The program aims at controlling the pollution in a given area by suggesting the number of trees and the areas where they should be planted. The heart of the program is Computer Vision. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Python languag
12 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Python - Add space between Numbers and Alphabets in String
In this article, we delve into a practical Python solution to improve text readability by adding spaces between numbers and alphabets in strings by utilizing Python's powerful string manipulation capabilities. Input: test_str = 'ge3eks4geeks is1for10geeks' Output: ge 3 eks 4 geeks is 1 for 10 geeks Explanation: Numbers separated from Characters. Ad
9 min read
PyCairo - Transform a distance vector from device space to user space
In this article, we will learn how we can transform a distance-vector from device space to user space using PyCairo in python. This function is similar to Context.device_to_user() except that the translation components of the inverse CTM will be ignored when transforming (dx,dy). Pycairo is a Python module providing bindings for the cairo graphics
2 min read
PyCairo - How we Can transform a coordinate from device space to user space ?
In this article, we will learn how we Can transform a coordinate from device space to user space using PyCairo in python. Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM). Pycairo is a Python module providing bindings for the cairo graphics library. This
2 min read
Add space between histogram bars in Matplotlib
Matplotlib is a plotting library in Python programming language and it's by default numerical mathematics extension of NumPy library in python language. While programming in python language we use the matplotlib library package for graph and histogram visualizations. But while plotting histogram using matplotlib in python, it lacks division or spac
2 min read
Python - Remove space between tuple elements
Sometimes, while working with Tuples, we can have a problem in which we need to print tuples, with no space between the comma and next element, which by convention, is present. This problem can have use in day-day and school programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = (7, 6, 8) Output : (7, 6, 8
6 min read
Set the amount of vertical space between legend groups using Plotly-Python
In this article, we will learn how to set the amount of vertical space between legend groups. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes. Example 1: In this Bar chart, We are setting the amount of vertical space (in px) between legend groups with the help of a method called f
1 min read
Regex in Python to put spaces between words starting with capital letters
Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to lowercase Examples: Input : BruceWayneIsBatmanOut
2 min read
How to insert a space between characters of all the elements of a given NumPy array?
In this article, we will discuss how to insert a space between the characters of all elements of a given array of string. Example: Suppose we have an array of string as follows: A = ["geeks", "for", "geeks"] then when we insert a space between the characters of all elements of the above array we get the following output. A = ["g e e k s", "f o r",
1 min read
Practice Tags :