Converting Snake Case to Lower Camel Case (lowerCamelCase)

Posted on

Question :

Converting Snake Case to Lower Camel Case (lowerCamelCase)

What would be a good way to convert from snake case (my_string) to lower camel case (myString) in Python 2.7?

The obvious solution is to split by underscore, capitalize each word except the first one and join back together.

However, I’m curious as to other, more idiomatic solutions or a way to use RegExp to achieve this (with some case modifier?)

Asked By: luca

||

Answer #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'
Answered By: jbaiter

Answer #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)])
Answered By: Berislav Lopac

Answer #3:

Obligatory one-liner:

import string

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

Answer #4:

>>> snake_case = "this_is_a_snake_case_string"
>>> l = snake_case.split("_")
>>> print l[0] + "".join(map(str.capitalize, l[1:]))
'thisIsASnakeCaseString'
Answered By: Leon Young

Answer #5:

another one liner

def to_camel_case(snake_string):
    return snake_string.title().replace("_", "")
Answered By: steve

Answer #6:

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
Answered By: Glenn Dills

Answer #7:

Building on Steve’s answer, this version should work:

def to_camel_case(snake_case_string):
    titleCaseVersion =  snake_case_string.title().replace("_", "")
    camelCaseVersion = titleCaseVersion[0].lower() + titleCaseVersion[1:]
    return camelCaseVersion
Answered By: MLev

Answer #8:

Here is a solution using regular expressions:

import re

def snake_to_camel(text):
    return re.sub('_([a-zA-Z0-9])', lambda m: m.group(1).upper(), text)
Answered By: Antoine Pinsard

Leave a Reply

Your email address will not be published. Required fields are marked *