Python - Add Space between Potential Words
Last Updated :
08 May, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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
OutputThe 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))
OutputThe 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)
OutputThe 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
Python - Add K between case shifts
Given a string, the task is to add K when a case shift happens. Input : test_str = 'GeeKSforGeEKs', K = '*' Output : G*ee*KS*for*G*e*EK*s Explanation : After G, lowercase character e is present, * is inserted in between. Same goes for each insertion. Input : test_str = 'GeeKS', K = '*' Output : G*ee
5 min read
Python - Avoid Spaces in string length
When working with strings in Python, we may sometimes need to calculate the length of a string excluding spaces. The presence of spaces can skew the length when we're only interested in the number of non-space characters. Let's explore different methods to find the length of a string while ignoring
3 min read
Python - Replace words from Dictionary
Replacing words in a string using a dictionary allows us to efficiently map specific words to new values. Using str.replace() in a LoopUsing str.replace() in a loop, you can systematically replace specific substrings within a string with new values. This approach is useful for repetitive replacement
3 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
6 min read
Python program to count words in a sentence
In this article, we will explore different methods for counting words in a sentence. The split() method is one of the simplest and most efficient ways to count words in a sentence.Pythons = "Python is fun and versatile." # Counting words word_count = len(s.split()) print(word_count) Output5 Explanat
2 min read
Python - Replace all words except the given word
Given a string. The task is to replace all the words with '?' except the given word K. Examples: Input : test_str = 'gfg is best for geeks', K = "gfg", repl_char = "?" Output : gfg ? ? ? ? Explanation : All words except gfg is replaced by ?. Input : test_str = 'gfg is best for gfg', K = "gfg", repl_
6 min read
Python - Sequence Assignment to Words
Given a String of words, assign an index to each word. Input : test_str = 'geeksforgeeks is best' Output : {0: 'geeksforgeeks', 1: 'is', 2: 'best'} Explanation : Index assigned to each word. Input : test_str = 'geeksforgeeks best' Output : {0: 'geeksforgeeks', 1: 'best'} Explanation : Index assigned
5 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
9 min read
Replace multiple words with K - Python
We are given a string s and the task is to replace all occurrences of specified target words with a single replacement word K.For example, given text = "apple orange banana" and words_to_replace = ["apple", "banana"], the output will be "K orange K".Using List ComprehensionThis is the most efficient
4 min read
Get number of characters, words, spaces and lines in a file - Python
Given a text file fname, the task is to count the total number of characters, words, spaces, and lines in the file. As we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to calculate the total number of characters, words, spaces, and line
5 min read