Converting Snake Case to Lower Camel Case (lowerCamelCase)

PythonPython 2.7

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

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

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

Obligatory one-liner:

import string

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

Solution 5 - Python

another one liner

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

Solution 6 - Python

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

Solution 7 - Python

for one-line fans..

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

Solution 8 - Python

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

Solution 9 - Python

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:] )

Solution 10 - Python

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)

Solution 11 - Python

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/

Solution 12 - Python

def to_camel_case(snake_str):
    components = snake_str.split('_')
    return reduce(lambda x, y: x + y.title(), components[1:], components[0])

Solution 13 - Python

Without using list comprehensions:

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

Solution 14 - Python

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

Solution 15 - Python

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

Solution 16 - Python

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('_'))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlucaView Question on Stackoverflow
Solution 1 - PythonjbaiterView Answer on Stackoverflow
Solution 2 - PythonBerislav LopacView Answer on Stackoverflow
Solution 3 - PythonGlenn DillsView Answer on Stackoverflow
Solution 4 - PythonSimeon VisserView Answer on Stackoverflow
Solution 5 - PythonsteveView Answer on Stackoverflow
Solution 6 - PythonLeon YoungView Answer on Stackoverflow
Solution 7 - PythonTearf001View Answer on Stackoverflow
Solution 8 - PythonMLevView Answer on Stackoverflow
Solution 9 - PythonBlessed GeekView Answer on Stackoverflow
Solution 10 - PythonAntoine PinsardView Answer on Stackoverflow
Solution 11 - PythonBaiJiFeiLongView Answer on Stackoverflow
Solution 12 - PythonChandler ChildsView Answer on Stackoverflow
Solution 13 - PythonSyasView Answer on Stackoverflow
Solution 14 - PythonMike StarovView Answer on Stackoverflow
Solution 15 - PythonSteve WellsView Answer on Stackoverflow
Solution 16 - PythonHemingway_PLView Answer on Stackoverflow