Converting Snake Case to Lower Camel Case (lowerCamelCase)

Solution 1:

def to_camel_case(snake_str):
    components = snake_str.split('_')
    # We capitalize the first letter of each component except the first one
    # with the 'title' method and join them together.
    return components[0] + ''.join(x.title() for x in components[1:])

Example:

In [11]: to_camel_case('snake_case')
Out[11]: 'snakeCase'

Solution 2:

Here's yet another take, which works only in Python 3.5 and higher:

def camel(snake_str):
    first, *others = snake_str.split('_')
    return ''.join([first.lower(), *map(str.title, others)])

Solution 3:

A little late to this, but I found this on /r/python a couple days ago:

pip install pyhumps

and then you can just do:

import humps

humps.camelize('jack_in_the_box')  # jackInTheBox
# or
humps.decamelize('rubyTuesdays')  # ruby_tuesdays
# or
humps.pascalize('red_robin')  # RedRobin

Solution 4:

Obligatory one-liner:

import string

def to_camel_case(s):
    return s[0].lower() + string.capwords(s, sep='_').replace('_', '')[1:] if s else s