How to Convert camelCase to snake_case in Python

4 min read

Converting camelCase to snake_case is one of the most common string transformations in Python, especially when working with JavaScript APIs.

Method 1: Regex

import re
def camel_to_snake(name):
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

print(camel_to_snake("getUserById"))  # get_user_by_id

Method 2: Manual Loop

def camel_to_snake(name):
    result = [name[0].lower()]
    for char in name[1:]:
        if char.isupper():
            result.append('_')
        result.append(char.lower())
    return ''.join(result)

Method 3: inflection Library

import inflection
inflection.underscore("getUserById")  # "get_user_by_id"

Converting JSON Keys

def convert_keys(obj):
    if isinstance(obj, dict):
        return {camel_to_snake(k): convert_keys(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [convert_keys(i) for i in obj]
    return obj

Online Tool

For quick conversions, use our snake_case converter or case converter hub.