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?)
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'
>>> snake_case = "this_is_a_snake_case_string"
>>> l = snake_case.split("_")
>>> print l[0] + "".join(map(str.capitalize, l[1:]))
'thisIsASnakeCaseString'
Obligatory one-liner:
import string
def to_camel_case(s):
return s[0].lower() + string.capwords(s, sep='_').replace('_', '')[1:] if s else s
another one liner
def to_camel_case(snake_string):
return snake_string.title().replace("_", "")
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
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)])
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)
def to_camel_case(snake_str):
components = snake_str.split('_')
return reduce(lambda x, y: x + y.title(), components[1:], components[0])
Without using list comprehensions:
def snake_to_camel_case(text_snake):
return '{}{}'.format(
text_snake[:1].lower(),
text_snake.title().replace('_', '')[1:],
)
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
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))
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:] )
for one-line fans..
''.join((wd.title() if i else wd) for (i,wd) in enumerate(string.split('_')))
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
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
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('_'))
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?)
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'
>>> snake_case = "this_is_a_snake_case_string"
>>> l = snake_case.split("_")
>>> print l[0] + "".join(map(str.capitalize, l[1:]))
'thisIsASnakeCaseString'
Obligatory one-liner:
import string
def to_camel_case(s):
return s[0].lower() + string.capwords(s, sep='_').replace('_', '')[1:] if s else s
another one liner
def to_camel_case(snake_string):
return snake_string.title().replace("_", "")
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
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)])
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)
def to_camel_case(snake_str):
components = snake_str.split('_')
return reduce(lambda x, y: x + y.title(), components[1:], components[0])
Without using list comprehensions:
def snake_to_camel_case(text_snake):
return '{}{}'.format(
text_snake[:1].lower(),
text_snake.title().replace('_', '')[1:],
)
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
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))
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:] )
for one-line fans..
''.join((wd.title() if i else wd) for (i,wd) in enumerate(string.split('_')))
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
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
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('_'))