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

PythonProgrammingServer Side Programming

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 −


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 −


 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()


This will give the output −

A Really Long Variable Name In Java
Published on 03-Aug-2018 06:02:31