0
0
PythonProgramBeginner · 2 min read

Python Program to Convert Camel Case to Snake Case

You can convert camel case to snake case in Python using re.sub(r'(? which inserts underscores before uppercase letters and then makes all letters lowercase.
📋

Examples

InputCamelCase
Outputcamel_case
InputthisIsCamelCase
Outputthis_is_camel_case
Inputalready_snake_case
Outputalready_snake_case
🧠

How to Think About It

To convert camel case to snake case, look for places where a capital letter appears after a lowercase letter or another capital letter (except at the start). Insert an underscore before that capital letter and then change the whole string to lowercase. This way, words joined in camel case become separated by underscores.
📐

Algorithm

1
Get the input camel case string.
2
Find each uppercase letter that is not at the start of the string.
3
Insert an underscore before each such uppercase letter.
4
Convert the entire string to lowercase.
5
Return the new snake case string.
💻

Code

python
import re

def camel_to_snake(text):
    return re.sub(r'(?<!^)(?=[A-Z])', '_', text).lower()

# Example usage
print(camel_to_snake('CamelCase'))
print(camel_to_snake('thisIsCamelCase'))
print(camel_to_snake('already_snake_case'))
Output
camel_case this_is_camel_case already_snake_case
🔍

Dry Run

Let's trace 'thisIsCamelCase' through the code

1

Input string

text = 'thisIsCamelCase'

2

Find uppercase letters not at start

Uppercase letters found at positions: 4 ('I'), 6 ('C'), 11 ('C')

3

Insert underscores before uppercase letters

String becomes 'this_Is_Camel_Case'

4

Convert to lowercase

Final string: 'this_is_camel_case'

IndexCharacterAction
0tNo change
1hNo change
2iNo change
3sNo change
4IInsert underscore before
5sNo change
6CInsert underscore before
7aNo change
8mNo change
9eNo change
10lNo change
11CInsert underscore before
12aNo change
13sNo change
14eNo change
💡

Why This Works

Step 1: Detect uppercase letters

The code uses a regular expression to find uppercase letters that are not at the start of the string using (?.

Step 2: Insert underscores

It inserts an underscore before each uppercase letter found, effectively separating words.

Step 3: Convert to lowercase

Finally, the entire string is converted to lowercase to match snake case style.

🔄

Alternative Approaches

Manual loop and build
python
def camel_to_snake_manual(text):
    result = ''
    for char in text:
        if char.isupper():
            if result:
                result += '_'
            result += char.lower()
        else:
            result += char
    return result

print(camel_to_snake_manual('CamelCase'))
This method uses a loop and checks each character, which is easy to understand but less concise than regex.
Using re.findall and join
python
import re

def camel_to_snake_findall(text):
    words = re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?![a-z])', text)
    return '_'.join(word.lower() for word in words)

print(camel_to_snake_findall('CamelCase'))
This splits the string into words first, then joins with underscores. It handles some edge cases better but is more complex.

Complexity: O(n) time, O(n) space

Time Complexity

The program scans the input string once, checking each character with regex, so it runs in linear time relative to the string length.

Space Complexity

It creates a new string with underscores and lowercase letters, so space used grows linearly with input size.

Which Approach is Fastest?

The regex re.sub method is concise and efficient for typical use, while manual loops may be easier to understand but slightly slower.

ApproachTimeSpaceBest For
Regex re.subO(n)O(n)Concise and fast for most cases
Manual loopO(n)O(n)Simple logic, easy to customize
Regex findall + joinO(n)O(n)Better word splitting, handles edge cases
💡
Use Python's re.sub with a lookahead to insert underscores before uppercase letters for a clean conversion.
⚠️
Beginners often forget to handle the first character separately, adding an unwanted underscore at the start.