Signup/Sign In

Python Program to put spaces between words starting with capital letters using Regex

In this tutorial, we will learn to put space between words starting with capital letters. There is a set of words in a sentence and each word starts with an uppercase letter and there is no space between the words. So, we need to add space between each word. We will be using regex to do so.

Python Regex also called REs or regular expressions is a module using which we can specify rules to set the possible strings to match. It is available in re module.

Look at the examples to understand the input and output format.

Input: 'HelloWorldOfPython'

Output: Hello World Of Python

Input: 'LetUsStudyPython'

Output: Let Us Study Python

To add space between each word, we will use the following approach.

We will use re.findall() method to get the list of Words.

To extract the Words, use '[A-Z][a-z]*' expression. The following regular expression describes a word starting with an uppercase letter followed by multiple lowercase letters.

Approach: Using findall() method

In this method, we will find the words within the input string using re.findall() method, then we will concatenate it by add space between each word.

Algorithm

Step1: Import re module

Step2: Define a regex expression for separating the words.

Step3: Use the regex method to list out the words in the string.

Step4: Concatenate each word in the list with a space between them.

Step5: Print the output

Python Program 1

In this example, we will add space between each word which starts with a capital letter using regex.

# import module for regular expression 
import re
#input
string='HelloWorldOfPython'
#Find the words in string starting with uppercase letter. 
words = re.findall('[A-Z][a-z]*', string)
#concatenate the word with space
print(' '.join((words)))

Here is the output of the above code.


Hello World Of Python

Python Program 2

Let us take another example to add space between words.

# import module for regular expression 
import re
#input
string='LetUsStudyPython'
#Find the words in string starting with uppercase letter. 
words = re.findall('[A-Z][a-z]*', string)
#concatenate the word with space
print(' '.join((words)))

Here is the above code


Let Us Study Python

Conclusion

In this tutorial, we have learned to add space between words starting with a capital letter in the given string with regex. It has been explained with examples.