Fundamentals 5 min read

How to Split CamelCase Strings in Python: 5 Practical Methods

This article walks through five Python techniques for converting CamelCase strings like "WeLovePython" into space‑separated, properly capitalized sentences, explaining each approach, showing complete code examples, and comparing their outputs.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Split CamelCase Strings in Python: 5 Practical Methods

In a recent Python community discussion, a user asked how to transform a CamelCase string like "WeLovePython" into a space‑separated, properly capitalized sentence such as "We love python".

1. Introduction

The original text shows the desired transformation and explains that the first character should remain uppercase while the rest become lowercase.

2. Implementation

Several solutions were shared.

First approach iterates over each character, inserts a space before uppercase letters, then trims the leading space.

# coding:utf-8
# @Time : 2022/5/4 11:46
# @Author: PiPi
text = "WeLovePython"
res = ''.join([" " + i if i.isupper() else i for i in text]).strip()
print(res)

This produces "We LovePython". To also lowercase the rest of the letters, an additional step is added:

text = "WeLovePython"
res = ''.join([" " + i if i.isupper() else i for i in text]).strip()
b = res[0] + ''.join([i.lower() for i in res[1:]])
print(b)

Another variant builds the result directly and then applies .lower() and .capitalize():

text = "WeLovePython"
res = text[0] + ''.join([" " + i if i.isupper() else i for i in text[1:]]).lower()
print(res)

res = ''.join([" " + i if i.isupper() else i for i in text]).strip().capitalize()
print(res)

A regular‑expression solution was also presented:

import re
text = "WeLovePython"
result = re.sub(r'\w[A-Z]', lambda x: ' '.join(x.group(0).lower()), text)
print(result)

Each method ultimately yields the desired output "We love python".

3. Summary

The article reviews five different ways to split and reformat CamelCase strings in Python, all based on detecting uppercase letters and inserting spaces, with variations in how the final capitalization is handled.

Pythoncode-exampleregular expressionsstring-manipulationCamelCase
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.