
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Put Spaces Between Words Starting with Capital Letters in Python
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
Advertisements