
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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
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
- Related Articles
- c# Put spaces between words starting with capital letters
- How to find capital letters with Regex in MySQL?
- Program to rearrange spaces between words in Python
- How to input letters in capital letters in an edit box in Selenium with python?
- Setting Spaces between Letters with CSS letter-spacing Property
- MySQL update query to remove spaces between letters?
- How do i match just spaces and newlines with Python regex?
- Python Program that extract words starting with Vowel From A list
- How to put space between words that start with uppercase letter in string vector in R?
- How to set the font to be displayed in small capital letters with JavaScript?
- Program to find all words which share same first letters in Python
- Given below is a crossword puzzle based on this lesson. Use hints to fill in the blank spaces with letters that complete the words."\n
- Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character
- How to remove white spaces using Java Regular Expression (RegEx)
- Python regex to find sequences of one upper case letter followed by lower case letters

Advertisements