Python Program to Convert Camel Case to Snake Case
re.sub(r'(? which inserts underscores before uppercase letters and then makes all letters lowercase.Examples
How to Think About It
Algorithm
Code
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'))
Dry Run
Let's trace 'thisIsCamelCase' through the code
Input string
text = 'thisIsCamelCase'
Find uppercase letters not at start
Uppercase letters found at positions: 4 ('I'), 6 ('C'), 11 ('C')
Insert underscores before uppercase letters
String becomes 'this_Is_Camel_Case'
Convert to lowercase
Final string: 'this_is_camel_case'
| Index | Character | Action |
|---|---|---|
| 0 | t | No change |
| 1 | h | No change |
| 2 | i | No change |
| 3 | s | No change |
| 4 | I | Insert underscore before |
| 5 | s | No change |
| 6 | C | Insert underscore before |
| 7 | a | No change |
| 8 | m | No change |
| 9 | e | No change |
| 10 | l | No change |
| 11 | C | Insert underscore before |
| 12 | a | No change |
| 13 | s | No change |
| 14 | e | No 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
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'))
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'))
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Regex re.sub | O(n) | O(n) | Concise and fast for most cases |
| Manual loop | O(n) | O(n) | Simple logic, easy to customize |
| Regex findall + join | O(n) | O(n) | Better word splitting, handles edge cases |
re.sub with a lookahead to insert underscores before uppercase letters for a clean conversion.