Converting Snake Case to Lower Camel Case (lowerCamelCase)

Question:

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

||

Answers:

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
>>> 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

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

another one liner

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

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

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

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
def to_camel_case(snake_str):
    components = snake_str.split('_')
    return reduce(lambda x, y: x + y.title(), components[1:], components[0])
Answered By: Chandler Childs

Without using list comprehensions:

def snake_to_camel_case(text_snake):
    return '{}{}'.format(
        text_snake[:1].lower(),
        text_snake.title().replace('_', '')[1:],
    )
Answered By: Syas

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

So I needed to convert a whole file with bunch of snake case parameters into camel case. The solution by Mathieu Rodic worked best. Thanks.

Here is a little script to use it on files.

import re

f = open("in.txt", "r")
words = f.read()

def to_camel_case3(s):
    return re.sub(r'_([a-z])', lambda x: x.group(1).upper(), s)

f = open("out.txt", "w")
f.write(to_camel_case3(words))
Answered By: Mike Starov
def toCamel(snake)
    return ''.join( word.capitalize()
                    for word in snake.split('_') )

Allow underscore to be escaped by a preceding underscore (e.g. ‘Escaped__snake’ would become ‘Escaped_Snake’, while ‘usual_snake’ becomes ‘UsualSnake’. Include ternary test for blank.

def toCamel(escaped_snake)
    return ''.join( (word.capitalize(), '_')[word=='')
                    for word in escaped_snake.split('_') )

Don’t capitalize the 1st segment (i.e, ‘tHERE_is_a_snake’ becomes ‘thereIsASnake’)

def toCamel(esCAPed_snake)
    words = esCAPed_snake.split('_')
    return words[0].lower() + ''.join( (word.capitalize(), '_')[word=='')
                                       for word in words[1:] )
Answered By: Blessed Geek

for one-line fans..

''.join((wd.title() if i else wd) for (i,wd) in enumerate(string.split('_')))
Answered By: Tearf001

You can use pydash if you are familiar with lodash.

pip install pydash first.

import pydash  # pip install pydash

assert pydash.snake_case("WriteLine") == "write_line"
assert pydash.snake_case("writeLine") == "write_line"
assert pydash.camel_case("write_line") == "writeLine"
assert pydash.upper_first(pydash.camel_case("write_line")) == "WriteLine"

https://github.com/dgilland/pydash

https://pydash.readthedocs.io/en/latest/

https://pypi.org/project/pydash/

Answered By: BaiJiFeiLong

it this too simple?

snake_case is already lowercase. my_string

So if we title the string and remove the underscores MyString

then replace the first character M with the original m we’re done.

scase = "my_string"
ccase = scase[0] + scase.title().replace('_', '')[1:]

output:
myString

Answered By: Steve Wells

I personally use this solution since it is a rolling transformation:

from functools import reduce

def camelize(snake_string: str) -> str:
    return reduce(lambda x, y: x + y.capitalize(), snake_string.split('_'))
Answered By: Hemingway_PL
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.