Reputation: 12601
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?)
Upvotes: 123
Views: 94847
Reputation: 34972
Here is a solution using regular expressions:
import re
def snake_to_camel(text):
return re.sub('_([a-zA-Z0-9])', lambda m: m[1].upper(), text)
Upvotes: 3
Reputation: 7099
def to_camel_case(snake_str):
return "".join(x.capitalize() for x in snake_str.lower().split("_"))
def to_lower_camel_case(snake_str):
# We capitalize the first letter of each component except the first one
# with the 'capitalize' method and join them together.
camel_string = to_camel_case(snake_str)
return snake_str[0].lower() + camel_string[1:]
Example:
In [11]: to_lower_camel_case('snake_case')
Out[11]: 'snakeCase'
In [12]: to_lower_camel_case('SNAKE_Case')
Out[12]: 'snakeCase'
In [13]: to_lower_camel_case('SNAKE_CASE')
Out[13]: 'snakeCase'
Upvotes: 221
Reputation: 21
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('_'))
Upvotes: 2
Reputation: 164
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
Upvotes: 5
Reputation: 4635
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/
Upvotes: 1
Reputation: 131
''.join((wd.title() if i else wd) for (i,wd) in enumerate(string.split('_')))
Upvotes: 4
Reputation: 21664
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:] )
Upvotes: 2
Reputation: 17243
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)])
Upvotes: 31
Reputation: 7296
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))
Upvotes: 0
Reputation: 281
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
Upvotes: 28
Reputation: 115
Without using list comprehensions:
def snake_to_camel_case(text_snake):
return '{}{}'.format(
text_snake[:1].lower(),
text_snake.title().replace('_', '')[1:],
)
Upvotes: 0
Reputation: 1
def to_camel_case(snake_str):
components = snake_str.split('_')
return reduce(lambda x, y: x + y.title(), components[1:], components[0])
Upvotes: 0
Reputation: 435
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
Upvotes: 3
Reputation: 163
another one liner
def to_camel_case(snake_string):
return snake_string.title().replace("_", "")
Upvotes: 12
Reputation: 122376
Obligatory one-liner:
import string
def to_camel_case(s):
return s[0].lower() + string.capwords(s, sep='_').replace('_', '')[1:] if s else s
Upvotes: 9
Reputation: 585
>>> snake_case = "this_is_a_snake_case_string"
>>> l = snake_case.split("_")
>>> print l[0] + "".join(map(str.capitalize, l[1:]))
'thisIsASnakeCaseString'
Upvotes: 5