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 following amendments:
(i) Put a single space between these words.
(ii) Convert the uppercase letters to lowercase.

Examples:

Input : BruceWayneIsBatman
Output : bruce wayne is batman

Input :  GeeksForGeeks
Output :  geeks for geeks

We have 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 capital letter using re.findall(expression, str) method.
  2. Now change capital letter of each word to lowercase and concatenate each word with space.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Put spaces between words starting with
# capital letters using Regex in Python
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
    result = []
    for word in words:
        word = chr( ord (word[0]) + 32) + word[1:]
        result.append(word)
    print ' '.join(result)
  
# Driver program
if __name__ == "__main__":
    input = 'BruceWayneIsBatman'
    putSpace(input)

chevron_right


Output:

bruce wayne is batman

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.