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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 11 views 0 copies

Python code

12 lines
Python 3.9+
def 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

stdout
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

  1. Use a regex approach: `re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower()` for a one-liner
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.