How to Convert camelCase to snake_case in Python
Convert camelCase strings to snake_case using a simple Python function that inserts underscores before uppercase letters and lowercases everything.
Python code
12 linesdef camel_to_snake(s):
result = ""
for i, char in enumerate(s):
if char.isupper() and i > 0:
result += "_"
result += char.lower()
return result
if __name__ == "__main__":
test_cases = ["camelCase", "helloWorld", "thisIsACoolExample", "already_snake", "UPPER"]
for case in test_cases:
print(f"{case} -> {camel_to_snake(case)}")
Output
camelCase -> camel_case
helloWorld -> hello_world
thisIsACoolExample -> this_is_a_cool_example
already_snake -> already_snake
UPPER -> upper
How it works
The function iterates through each character using enumerate. When a character is uppercase and it's not the first character (index > 0), it prepends an underscore to separate words. Each character is then converted to lowercase. This produces clean snake_case output while leaving already-snake_case strings unchanged. The if __name__ == "__main__" guard allows the function to be imported elsewhere without running the test cases.
Common mistakes
- Not checking `i > 0`, which adds a leading underscore for strings that start uppercase
- Forgetting to lowercase the characters, resulting in mixed-case output
- Assuming the function handles acronyms correctly — consecutive capitals become `_a_c_r_o` instead of `acro`
Variations
- Use a regex approach: `re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower()` for a one-liner
- Use `re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s).lower()` to handle digit-letter boundaries
Real-world use cases
- Normalizing database column names from API camelCase payloads to snake_case table fields.
- Converting configuration keys between different style conventions when integrating multiple services.
- Preparing output for linter-friendly code in projects that enforce snake_case naming for variables.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.