Monday, November 24, 2025
HomeLanguagesRegex in Python to put spaces between words starting with capital letters

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: 

  1. Put a single space between these words. 
  2. Convert the uppercase letters to lowercase 

Examples: 

Input : BruceWayneIsBatman
Output : bruce wayne is batman

Input : GeeksForGeeks
Output : Lazyroar for Lazyroar

Regex in Python to put spaces between words starting with capital letters

We have an existing solution for this problem, please refer Put spaces between words starting with capital letters link. 

We can solve this problem quickly in python using findall() method of re (regex) library

Approach : 

  1. Split each word starting with a capital letter using re.findall(expression, str) method.
  2. Now change the capital letter of each word to lowercase and concatenate each word with space.

Implementation:

Python3




import re
   
def putSpace(input):
   
    # regex [A-Z][a-z]* means any string starting 
    # with capital character followed by many 
    # lowercase letters 
    words = re.findall('[A-Z][a-z]*', input)
   
    # Change first letter of each word into lower
    # case
    for i in range(0,len(words)):
      words[i]=words[i][0].lower()+words[i][1:]
    print(' '.join(words))
     
   
# Driver program
if __name__ == "__main__":
    input = 'BruceWayneIsBatman'
    putSpace(input)


Output

bruce wayne is batman

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

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32411 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6786 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6910 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6866 POSTS0 COMMENTS
Umr Jansen
6853 POSTS0 COMMENTS