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


The problem we are trying to solve here is to convert CamelCase to separate out words. We can solve this directly using regexes by finding all occurrences of a capital letter in the given string and put a space before it. We can use the sub method from the re module.

For example, for the input string −

AReallyLongVariableNameInJava

We should get the output −

A Really Long Variable Name In Java

We can use "[A-Z]" regex to find all uppercase letters, then replace them with space and that letter again. We can implement it using the re package as follows −

Example

 Live Demo

import re

# Find and capture all capital letters in a group and make that replacement
# using the \1 preceded by a space. Strip the string to remove preceding
# space before first letter.
separated_str = re.sub("([A-Z])", " \1", "AReallyLongVariableNameInJava").strip()
print(separated_str)

Output

This will give the output −

A Really Long Variable Name In Java

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

578 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements